Caution while using CSS Siblings selectors

CSS3 has introduced a new sibling selector as ‘~’. Using this selector we can select all the elements which are sibling to another element. It can be used like div ~ p.

There was an already existing sibling selector in CSS2 as ‘+’. Using this selector, we could select the immediate siblings of an element and could be used like div + p.

This way, now with CSS3 there is another option of selecting the siblings. But before start using these selectors, there is one fine point to note about them.

That is, when we use these selectors then it would select only those sibling elements which appear after the main element. For example, if we use the following code:

div ~ p

Then in this case, all the <p> tags which are after <div> tag, where both have common parent would be selected. Note that if there is any <p> tag which has common parent with a <div> tag but appears before the <div> tag will not be considered to be a sibling in this case and thus would not be selected.

This way, using a sibling selector does not allow selection of elements which are present prior to main element in the DOM tree. This may contradict the use of term sibling which emphasizes that the siblings are the ones which have common parents, but in case of CSS, siblings should have common parent along with the fact that the second element should appear after the first one in DOM tree.

Thus, be cautioned that if you use CSS sibling selectors, you will not be able to select those elements which are preceding the main element.

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