Why is descendant p not red in this case?
h2 p {
color: red;
}
<h2>h2
<h3>h3</h3>
<p>p</p>
</h2>
The reason is simple and somehow logical:
You are not allowed to nest heading elements
Simply becasue there is no logical reason for doing this. Headings obey to some rules in order to define the semantic of your web page and you broke one of it.
If you validate your code you will get an error like this:
Basically your browser is changing your HTML structure and you will have something like this:
As you can see your p
element no more belong to the h2
thus it won't get colored. So the solution is to avoid nesting headings element.
As a side note, if the p
is placed before h3
your code will work because the browser will break the structure when it will find the h3
and it will then immediately close the h2
.
h2 p {
color: red;
}
<h2>h2
<p>p</p>
<h3>h3</h3>
</h2>
Update
I rephrase the answer to make it more clear.
First of all. No, you can't contain any tag inside header tag while expecting it running as usual.
In MDN, it is stated that
Permitted content Phrasing content.
What is phrasing content? Take a look on MDN doc again.
Simply speak it is those tag is only the text and the mark-up of text, <p>
is not included. While for those included, CSS is not applicable.
That is why normally no element is added between heading element.
The reason why <p>
is not in red can be shown by simple step.
<p>
As this
<h2> h2
</h2>
<h3>h3</h3>
<p>p</p>
<p>
.<h3>h3<h3>
on top of <p>p<p>
.<p>
can maintain its red color, which means CSS already does its work.Therefore the problem is caused by browser parsing the <h2><h3></h3></h2>
into <h2></h2><h3></h3>
. That's why pre-set CSS cannot take effect.
Special added
As mentioned by @Alohci, if we use the DOM, sample in this JSfiddle
The result is the same as we manually drag h3 element on top of p element.
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