Code Lover
Code Lover

Reputation: 8378

Where I can use + and > in CSS?

This may be a basic question but to me it is still confusing where I can use + or > in CSS.

I see many selectors like li > a or div + span etc. but I am not sure what the difference is and when to use them?

Upvotes: 19

Views: 15122

Answers (5)

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

The selectors are extensively explained in the W3 CSS spec, but here is a digest:

Immediate child selector

The > selector is the immediate child selector. In your example li > a, the rule would select any <a> element that is an immediate child of an <li> element.

The rule would select the anchor in this example:

<ul>
   <li><a href="#">An anchor</a></li>
</ul>

The adjacent sibling selector

The + selector is the adjacent sibling selector. In your example div + span, the rule would select any <span> elements that is immediately preceded by a <div> element, and where they both share the same parent.

The span element would be selected in this case:

<article>
   <div>A preceding div element</div>
   <span>This span would be selected</span>
</article>

Upvotes: 6

Gabe
Gabe

Reputation: 50523

The > sign means select a direct descendant

Example:

CSS

div > ul {
   list-style: none;
}

HTML Here the style would apply to the <ul>

<div>
  <ul>
  </ul>
</div>

The + sign means select an adjacent sibling

Example:

CSS

p + p
{
   font-weight: bold;
} 

HTML Here the style would apply to the latter <p>

<div>
   <p></p>
   <p></p>
</div>

Upvotes: 37

Dale
Dale

Reputation: 10469

I'm not sure about the + sign but the > sign in css means direct child of, consider this

div > h1 { color: red; }

This will style all h1 tags that are a direct child of a div.

<h1>BLAH</h1>
<div>
    <h1>BLAH</h1>
</div>

In that case the first h1 would be left alone, the second because it is a direct child of the div tag would be red.

Upvotes: -1

Bojangles
Bojangles

Reputation: 101533

The > is the direct child selector. In your example of li > a, this will only select <a> tags that are direct descendants of the <li>.

The + means siblings of the selected elements. In your example, div + span would select any <span>s next to a <div> (with the same parent).

Upvotes: 2

powerbuoy
powerbuoy

Reputation: 12848

li > a would only select a elements that are direct descendants of li elements. div + span would only select span elements that follow a div element.

Read more in @bažmegakapa's link: http://www.w3.org/TR/CSS2/selector.html#pattern-matching

Upvotes: 0

Related Questions