CSS-Adjacent Sibling Selector

We all know what are siblings Right? Persons who share the same parent. A similar concept is used in CSS. It is called the Adjacent Sibling Selector defined with ‘+’ sign. Since CSS style sheets sometimes contain hierarchical  selectors, it would be very useful to use them. We could selectively apply a style to a particular tag from a hierarchy.

Let’s see how.

sibling.png

So, Suppose we have some HTML like this

<h1>Apple</h1>
<p>Orange</p>
<p>Grapes</p>
<p>Peach</p>

And then we apply CSS on that

h1+p{
color:red;

}

Now from the CSS, you would know that definitely something would get a color of red. But which one of the 4 fruits, is going to get the color is a mystery 🙂 .

One thing to note is that a Browser reads a CSS file from Right to left. So, taking that analogy, if we go onto the first line, we see that there are two tags separated by a ‘+’ symbol. The browser would first read the tag ‘p’ and then it would search for it’s adjacent sibling which has a tag ‘h1’.

If we carefully look at the list, we would observe that the tag ‘p’ denoting Orange has the adjacent sibling ‘h1’ which is Apple. And hence the ‘p’ tag “Orange” would be colored red.

Hope this was something useful you learnt today 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s