A concept that confuses me when talking about HTML is adjacency , and we sib >.
What's the difference between siblings and adjacent siblings ?
A concept that confuses me when talking about HTML is adjacency , and we sib >.
What's the difference between siblings and adjacent siblings ?
Brothers are elements that are at the same level as the DOM tree:
<div>div1</div>
<div>div2</div>
<p>p1</p>
div1
, div2
, and p1
are brother elements, since they are on the same level.
Adjacent brother (in the singular as it is only one) is the element that is soon after. In the example above, div2
is adjacent sister of div1
, and p1
is adjacent brother of div2
.
According to the definition of the term adjacent :
Adjacent is an adjective that qualifies something that is next to, or either together or close to a certain thing.
In the case of CSS, it's something that comes LOGO after, even because the term Cascading Style Sheets (cascading style sheets) suggests elements always below the tree, like a cascade that always goes to low. You can not select upper or previous elements in the tree (except with JavaScript).
Another example:
<div id="pai">
<div>div1</div>
<div>div2</div>
</div>
<p>p1</p>
The elements div1
and div2
are siblings, since they are on the same level within div pai
. p1
is now sibling of div pai
, and p1
is sibling adjacent to div pai
because it comes right after and is at the same level in the tree.
In CSS you select siblings with the ~
sign between the elements and the adjacent ones with +
.
Select all siblings of #div1
and put the color red:
#div1 ~ *{
color: red;
}
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
<p>p1</p>
Select the adjacent sibling of #div1
and put the red color:
#div1 + *{
color: red;
}
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
<p>p1</p>