Style is not being applied to H1 element in CSS
Asked Answered
A

1

5

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>
Autoradiograph answered 15/6, 2016 at 14:31 Comment(2)
You cannot put an H1 in a paragraph, it's not valid.Rolon
webmasters.stackexchange.com/a/49449Imposition
P
12

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

Panek answered 15/6, 2016 at 14:33 Comment(3)
You can have a span inside a p tag or any other PhrasingElementImposition
On that note, the way to debug these sort of issues is to look at the generated DOM by browser using a browser inspector.Evaporation
@Panek awesome, saved my dayDonaldson

© 2022 - 2024 — McMap. All rights reserved.