【问题标题】:Style is not being applied to H1 element in CSS样式未应用于 CSS 中的 H1 元素
【发布时间】:2016-06-15 14:31:05
【问题描述】:

我遇到了一个奇怪的问题,样式未应用于H1 元素。

代码:

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

【问题讨论】:

标签: html css html-heading


【解决方案1】:

不能将标题(H1H6)作为 p 的子级,这是无效的 HTML。

这不起作用,因为您的浏览器会在 h1 元素开始之前自动关闭 p 元素,留下下面这个生成的 DOM(代码):

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

使用 F12 访问浏览器的开发工具或使用 CTRL + U 查看源代码,您可以看到生成的上面的 DOM。


相反,您可以在 p 或标题中添加 spanH1H6

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>

在 W3C 规范中查看有关 headings contentsphrasing elements 的更多信息

【讨论】:

  • 您可以在p 标记或任何其他PhrasingElement 中包含span
  • 请注意,调试此类问题的方法是使用浏览器检查器查看生成的 DOM。
  • @dippas 真棒,救了我的一天
猜你喜欢
  • 1970-01-01
  • 2011-04-08
  • 2010-10-12
  • 2010-12-22
  • 2017-10-04
  • 2012-08-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多