3

Look at this simple example:

<style>
   h1 {
      color: red;
   }
</style>

<h1>this is the 'h1'.<h2>this is the 'h2'</h2></h1>

I expected the color of the string within the 'h2' to be red, but it is still black.

This has confused me for a while. Why does it happen?

4

4 回答 4

9

An <h1> element is not permitted to contain <h2> elements (among others; only phrasing elements and text are permitted), so according to the spec that is invalid HTML.

The browser tries to compensate for the invalid HTML by considering that the <h2> is actually outside the <h1>, which leads to the observed result.

于 2013-09-18T09:03:24.260 回答
3

If you look at how the markup is rendered you will notice the h2 tag is rendered outside of the h1 tag.

Nesting these tags within each other is not proper syntax.

Rendered Markup

<h1>this is the 'h1'.</h1>
<h2>this is the 'h2'</h2>

Try switching the h2 with a span and styling as needed.

HTML

<h1>this is the 'h1'.<span>this is the 'h2'</span></h1>

CSS

h1.span{
   /*desired styling*/
}
于 2013-09-18T09:03:20.567 回答
0

you have set the color property only to tag h1 not to h2.

To overcome this, you can write class to set the same color for both the tags

<style>
   .color1 {
  color: red;
  }
</style>

<h1 class="color1">this is the 'h1'.<h2 class="color1">this is the 'h2'</h2></h1>
于 2013-09-18T09:03:11.417 回答
0

Quoted from HERE

HTML 4.01’s DTD, for example, says that H1-H6 are block-level elements with an inline content model. So for layout purposes, they appear on a new line, but for content purposes, they shouldn’t contain other block-level elements.

于 2013-09-18T09:07:26.927 回答