Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 742
Code Lover Avatar asked Apr 14 '12 17:04

Code Lover


People also ask

What is the use of * in CSS?

The CSS Universal Selector The universal selector (*) selects all HTML elements on the page.

Has CSS selector can I use?

Presently, the CSS :has() selector is not widely supported by browsers; this selector only works in the latest version of Safari or via the experimental features flag in the latest version of Chrome. So for now, we must not use :has() in production.

How do you call a tag in CSS?

There are three main methods of accessing or referring to HTML elements in CSS: By referring to the HTML element by its HTML tag name, e.g. p to refer to the paragraph HTML tag – <p> By using an ID, e.g. <p id="red_text">Some text</p> By using a class, e.g. <p class="red_text">Some text</p>


3 Answers

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>
like image 112
Gabe Avatar answered Sep 22 '22 09:09

Gabe


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>
like image 40
Christofer Eliasson Avatar answered Sep 22 '22 09:09

Christofer Eliasson


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).

like image 40
Bojangles Avatar answered Sep 19 '22 09:09

Bojangles