Codementor Events

Advanced CSS Selectors

Published Jun 02, 2021
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 {…}
c1.png

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 {…}
c2.png

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 {…}
c3.png

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 {...}
с4.png

Selects all elements that have alt with exact value.

divalt=”something” {…}
с5.png

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” {…}
с6.png

Selects elements that start with a selector value.

divalt^=”something” {…}
с7.png

Selects elements that end with a selector value.

divalt$=”something” {…}
с8.png

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

Selects the last two div, they have to be siblings/share same parent
с9.png

:NOT(:LAST-CHILD) {…}

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

DIV:FIRST-OF-TYPE {…}

Select the first siblings of its type.
с11.png

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

Discover and read more posts from Ilia Webdev
get started