As far as I understand the general sibling selector in CSS selects the descending siblings of an element.
Consider the following code:
<head>
<style>
h3 ~ div {
color: #FF00FF;
}
</style>
</head>
<body>
<h3>Header 3</h3>
<div>Sibling divivion</div>
<p>
<p>Nested paragraph</p>
<div>Nested division</div>
</p>
</body>
I would expect the general sibling selector to target all descending siblings of h3 that are div elements.
Can someone explain why the "Nested division" is selected? I don't think it is a sibling of h3?
The general sibling selector (~) selects all elements that are next siblings of a specified element.
The adjacent sibling selector is different from the general sibling selector as it selects only the element that immediately follows an element, whereas the general sibling selector selects any element that follows an element.
+ will only select the first element that is immediately preceded by the former selector. ~ selector all the sibling preceded by the former selector. Save this answer.
One example of adjacent siblings is the EM and STRONG elements within the paragraph. In fact, the only place in Figure 1 where elements don't have adjacent siblings is where they don't have any siblings at all, such as the A element; and in the unordered list with three LI children.
The div
actually is a sibling of the h3
element. You can't have a p
element and a div
element inside a p
element:
"The P element represents a paragraph. It cannot contain block-level elements (including P itself)."
Reference: 9.3.1 Paragraphs: the P element
When the browser encounters the second paragraph, it will end the first paragraph, so the second paragraph and the div
element ends up after the first paragraph:
<h3>Header 3</h3>
<div>Sibling divivion</div>
<p></p>
<p>Nested paragraph</p>
<div>Nested division</div>
<p></p>
The ending tag for the paragraph is optional, so a paragraph ends either with an ending tag, or where the next block element starts. The intended closing tag for the first paragraph is missing a starting tag, and ends up as a separate paragraph.
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