Style is not being applied to H1 element in CSS

大憨熊 提交于 2019-12-01 18:18:22

问题


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>

回答1:


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



来源:https://stackoverflow.com/questions/37838366/style-is-not-being-applied-to-h1-element-in-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!