May 25, 2011

Understand ‘+’, ‘>’ and ‘~’ symbols in CSS Selector

It explains How to use different signs (+,> and ~) in CSS selector and their differences. Before starting, 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>

Space:

div#container p{
font-weight:bold;
}

It is the descendant selector. It will target all p tags within container div.

> Sign:

It will target elements which are DIRECT children of a particular element.

div#container > p {
  border: 1px solid black;
}

css selector

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

+ 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 {  
   color: green;  
} 

css selector

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.

~ 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:blue;
} 


css selector

It will target both second and third.

Hope, you enjoyed this.

24 comments

  1. Thanks for simplifying this. I was having a very difficult time in differentiating the adjacent child sibling declarations. You have cleared this up and really simplified the rest of the subjects in a cohesive and intelligible manner. Cheers, Kudos and a Chocolate Chip Cookie!!

  2. Very concise. To the point. Wonderful read and highly effective writing. Thank you very much for your time and best wishes to you and your blog.

  3. Thanks for a great tutorial! You have really helped. The 3rd party
    software we are working with has some bad code that was producing
    duplicate DIV’s with the same ID, so we had to temporary hide
    one of the containers until there is a permanent fix. The following code
    did the trick => #social + #social {display:none;}

Leave a Reply

Your email address will not be published. Required fields are marked *