I am digging into the difference between child and descendant selector. Accordingly to the documentation that I found and to this question CSS Child vs Descendant selectors I write this example:
<div>
<h2>h2 1</h2>
<h2>h2 2</h2>
<section>
section
<h1>h1 section's son
<h2>h2 section's nephew</h2>
</h1>
<h2>h2 section's son</h2>
</section>
<h2>h2 3</h2>
<h2>h2 4</h2>
</div>
css:
section > h2 {
color:red;
}
(fiddle here: http://jsfiddle.net/armdan/ksB6f/1/ )
I expected that in this example the "h2 section's nephew" will not be selected, but it is selected and it becomes red. I don't understand what I am missing.
It is probably because it is invalid for h1
to contain a h2
. If you change the h1
to an element that can contain h2
, like a div
, it works as you expect:
<div>
<h2>h2 1</h2>
<h2>h2 2</h2>
<section>
section
<div>h1 section's son
<h2>h2 section's nephew</h2>
</div>
<h2>h2 section's son</h2>
</section>
<h2>h2 3</h2>
<h2>h2 4</h2>
</div>
Background: the HTML5 spec for h1
says that it can only contain text and "phrasing elements" , which are:
There are a few things...
<h2>
cannot be contained inside <h1>
. section > h2
selects the <h2>
, that's directly under <section>
and not as a grand child element. In the latter case, you need to use section h2
. Workarounds would be changing your code this way to make it semantic:
<div>
<h2>h2 1</h2>
<h2>h2 2</h2>
<section>
section
<h1>h1 section's son</h1>
<h2>h2 section's nephew</h2>
<h2>h2 section's son</h2>
</section>
<h2>h2 3</h2>
<h2>h2 4</h2>
</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.