【问题标题】:CSS child selector applying to nested elements应用于嵌套元素的 CSS 子选择器
【发布时间】:2015-06-07 05:25:31
【问题描述】:

我想让作为 div foo 的直接子级的段落具有蓝色文本,而所有其他段落都具有蓝色文本,但我编写的 css 将该样式应用于嵌套

标签也包含在 div 中。

CSS:

p {
  color:red;
}

#foo > p{
 color: blue;
}

HTML

<html>
<head>
  <link type="test/css" rel="stylesheet" href="test.css"/>
</head>
<body>
  <div id="foo">
  <p>
      This is the first line.<br/>
      This is the second line
      <p>Nested Paragraph</p>
  </p>
  </div>
  <p>Paragraph in new div</p>
</body>
</html>

输出(铬)

这是第一行。 (蓝色的) 这是第二行(蓝色)

嵌套段落(蓝色)

新 div 中的段落(红色)

【问题讨论】:

  • 恐怕你必须编辑你的问题以使其更清晰......更清晰以使有点意义。

标签: css


【解决方案1】:

p 元素内部没有另一个 p 元素。浏览器行为是把嵌套的p 放在外面。因此,您的所有段落都是 #foo 元素的子元素。

以下 HTML:

<p>
    This is the first line.
    This is the second line
    <p>Nested Paragraph</p>
</p>

导致此输出:

<p>
    This is the first line.
    This is the second line
</p>
<p>Nested Paragraph</p>

在下面的小提琴中检查输出的 HTML,你可以看到我在说什么:https://jsfiddle.net/lmgonzalves/ahse0jzg/

【讨论】:

    【解决方案2】:

    &lt;p&gt; 元素只能包含phrasing content

    &lt;p&gt; 元素被视为flow content,因此您的标记无效且解析不佳。不能嵌套&lt;p&gt; 元素。

    您的 CSS 选择器可以使用正确的 HTML。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-15
      • 2023-03-23
      • 2014-08-05
      • 1970-01-01
      • 2016-11-30
      • 2015-02-27
      • 1970-01-01
      相关资源
      最近更新 更多