Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is CSS descendant not recognize?

Tags:

html

css

Why is descendant p not red in this case?

h2 p {
  color: red;
}
<h2>h2
  <h3>h3</h3>
  <p>p</p>
</h2>
like image 754
Django102 Avatar asked Nov 18 '22 06:11

Django102


2 Answers

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:

enter image description here

Basically your browser is changing your HTML structure and you will have something like this:

enter image description here

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>
like image 124
Temani Afif Avatar answered Jan 19 '23 08:01

Temani Afif


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.

  1. Use this JSfiddle or simply use the fiddle for OP in this page .
  2. Right click inspect the element of <p>
  3. Notice that the html parsed by browser will become the following.

As this

<h2> h2
</h2>
  <h3>h3</h3>
  <p>p</p>
  1. And then in this JSfiddle, still right click and inspect element <p>.
  2. As you can dynamically alter the page element, Drag the <h3>h3<h3> on top of <p>p<p>.
  3. You will notice the element <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.

like image 31
MT-FreeHK Avatar answered Jan 19 '23 10:01

MT-FreeHK