DEV Community

Cover image for Advanced CSS Selectors
Nill Webdev
Nill Webdev

Posted on

Advanced CSS Selectors

I am writing this article because I feel like we are focusing more and more on JS in the front-end world. Forgetting about CSS and HTML possibilities.

In this piece, I’ll cover some CSS selectors starting with a child selector and hope to finish with some more surprising one. Enjoy

CHILD SELECTOR

Direct child selector only identifying p elements that fall directly within an article element.

article > p {…}

CHILD

GENERAL SIBLING SELECTOR

General sibling selector selects elements that follow and shares the same parent. H2 the element must come after p element.

p ~ h2 {…}

SIBLING

ADJACENT SIBLING SELECTOR +

Adjacent Sibling Selector selects the element that directly follow and shares the same parent
Only p elements directly following img element will be selected.

img + p {…}

ADJACENT

ATTRIBUTE SELECTORS

Attribute selectors select an element based on the presence or/and value of given attribute. There are several types, examples below.

Selects all elements that have alt attribute.

divalt {...}

ATTRIBUTE SELECTORS

Selects all elements that have alt with exact value.

divalt=”something” {…}

SELECTORS

Selects elements that contain value but in selector also exact value. (simply needs to have the something anywhere in the value of the attribute)

divalt*=”something” {…}

elements

Selects elements that start with a selector value.

divalt^=”something” {…}

qwe

Selects elements that end with a selector value.

divalt$=”something” {…}

value

DIV:NTH-LAST-CHILD(2) {…}

Selects the last two div, they have to be siblings/share same parent

ntl

:NOT(:LAST-CHILD) {…}

Selects all elements which are not the last child. Combination of :not and :last-child.

not

DIV:FIRST-OF-TYPE {…}

Select the first siblings of its type.

first

Hope that helps. Please share your most interesting selectors in comments!

Top comments (0)