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?
The CSS Universal Selector The universal selector (*) selects all HTML elements on the page.
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.
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>
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>
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>
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With