May 25, 2011

Understand '+', '>' and '~' symbols in CSS Selector

This article explains how to use different signs like space, +(plus), >(greater than) and ~(tilde) in CSS selector and their differences. Before getting started, let us take a sample code to understand the signs.

<div id="container">            
   <p>First</p>
    <div>
        <p>Child Paragraph</p>
    </div>
   <p>Second</p>
   <p>Third</p>      
</div>


Here is outline structure for better understanding:
css selector

Video Tutorial:

Space:

It is the descendant selector. It allows you to style all the nested child elements of a parent element, regardless of how deep they are in the hierarchy.

div#container p{
  background-color:green;
}


It will target all p tags within container div in our example.

css selector descendant

> Sign:

It is a child selector, which selects DIRECT child elements of a specified parent element.

div#container > p {
  background-color:green;
} 

css selector descendant

It will target all P element which are direct children of container div, not children of child div.

+ (plus) Sign:

It is Adjacent sibling combinator. It combines two sequences of simple selectors having the same parent and the second one must come IMMEDIATELY after the first.

div + p {
  background-color:green;
}

css selector sibling

It will only select the first element that is immediately preceded by the former selector. In our example, it will target to Second ONLY because the owner P element comes just after Div tag.

~ (tilde) Sign:

It is general sibling combinator and similar to Adjacent sibling combinator. The difference is that the second selector does NOT have to immediately follow the first one means It will select all elements that is preceded by the former selector.

div ~ p{
  background-color:green;
}

css selector sibling

It will target all P elements which follows div i.e. both second and third.

In this post, we saw how the plus sign +, tilde ~, space and greater than > symbols are used as CSS selectors to target specific elements based on their relationship to other elements in the HTML structure.

Do let us know how you are using it practically?