Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

General sibling selector - odd behavior

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?

like image 244
Peter Avatar asked Dec 11 '14 22:12

Peter


People also ask

What is general sibling selector?

The general sibling selector (~) selects all elements that are next siblings of a specified element.

What is the difference between general sibling selector & adjacent sibling selector?

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.

What is the difference between '+' and '~' sibling selectors?

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

Which is an example of an adjacent sibling selector?

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.


1 Answers

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.

like image 133
Guffa Avatar answered Sep 22 '22 16:09

Guffa