Search code examples
htmlcsshtml-heading

Style is not being applied to H1 element in CSS


I'm facing a strange problem, the style is not being applied to the H1 element.

Code:

p h1 {
  color: red;
}
<p>
  <h1>This is a header</h1>
</p>


Solution

  • You can't have a heading (H1 to H6) as a child of a p, that's invalid HTML.

    It's not working because your browser is automatically closing the p element before the h1 element starts, leaving you with this generated DOM (code) below:

    <p> </p>
    <h1>This is a header</h1>
    <p> </p>
    

    Using either the F12 to acess your browser's developer tools or using CTRL + U to view the source code, you can see this generated DOM above.


    Instead, you can have a span inside a p or a heading (H1 to H6)

    h1 {
      color: red;
    }
    h2 span {
      color: green
    }
    p span {
      color: blue
    }
    <h1>This is a header</h1>
    <h2><span>This</span> is a second header</h2>
    <p><span>This</span> is a paragragh</p>

    See more about headings contents and phrasing elements in the W3C Specification