Sibling and children and adjacent sibling CSS selectors

As some general CSS selectors we will try sibling and children and Adjacent sibling  selectors in this article. We will see the differences and their usages.

General descendant selector

Basically if we ever wanted to select all descendant of an element we will use this selector. What we need is to give same style to all similar elements no matter how deep they are buried in that selector:

ul li { color: green;}

In this case we will select all lis items inside unordered list or nested inside its children.

Only child Selector

On the other hand we might need to select only the direct children of the unordered list. Meaning we only need elements of one level deep into the parent. We will have this code then:

ul > li { color : red; }

Visually this is the image of how it will look like from Chris Coyier’s article here:

Therefor we clearly see the difference between these two CSS selectors.

General sibling selector

Technically we need to know that this selector selects all siblings. Not just those who immediately succeed the first element but also also those who appear anywhere:

p ~ p { margin: 0 0 5px 0; }

We can see the visual showcase of this here in this image:

general sibling example

Although the last p element is not directly followed by an article but it has been selected by p ~ p selector as well.

Adjacent sibling selector

Finally we can combine both above CSS selectors and make an adjacent sibling selector which selects and element which directly follows the first element:

adjacent selector example

As a result the last p element is not selected by p + p selector this time which makes sense.

As an example you can see a pen I created using all these CSS selectors here:

Thank you for reading.

© 2020
Azadeh Faramarzi

This site is created and maintined by Azadeh Faramarzi , A passionate developer, sport and code lover who loves to share and write when she has some time.