Why is descendant p not red in this case?
h2 p {
color: red;
}
<h2>h2
<h3>h3</h3>
<p>p</p>
</h2>
Why is descendant p not red in this case?
h2 p {
color: red;
}
<h2>h2
<h3>h3</h3>
<p>p</p>
</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.
` is not phrasing content, yet without the `
.", making `h3` element possible to be placed inside `h2` and on top of `p`. `h2` is parsed as independent of `h3`, that is the reason why p is not red in usual way. I will rephrase the whole ans to make it more clear. If it is still problematic, I think you should provide a better ans.
– MT-FreeHK Jul 31 '18 at 15:42The 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>
many possible reasons :
you forget to put the css code into the right place or you not linking the stylesheet .. pb like that
order of css rules :
p{ color: red;}
p{ color: black;}
/* Paragraphs will be black*/
do not make heading inside heading .. illogic
refresh the page maybe
` as a descendant of `
`, because you have `
– Geshode Jul 31 '18 at 01:16` in it. At least it worked fine for me, when taking out the `
` tags. But if you want to keep the `
` tags, then it might be easier to get it to red via an id.