id元素的nth-child

时间:2016-12-30 12:54:51

标签: html css css-selectors

我想强调p id =“dd”的'第二段'。我可以和n-child一起做吗?当我在样式中添加“#dd”时,它就会停止工作。

<!DOCTYPE html>
<html>
<head>
<style> 
#dd p:nth-child(3) {
    background: red;
}
</style>
</head>
<body>
<p id="de">
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
</p>
<p id="dd">
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
</p>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

正如Muhammad Usman上面提到的那样,

您需要将<<p>更改为<div>可以。< / p>

#dd p:nth-child(3) {
  background: red;
}
<div id="de">
  <p>The first paragraph.</p>
  <p>The second paragraph.</p>
  <p>The third paragraph.</p>
  <p>The fourth paragraph.</p>
</div>
<div id="dd">
  <p>The first paragraph.</p>
  <p>The second paragraph.</p>
  <p>The third paragraph.</p>
  <p>The fourth paragraph.</p>
</div>

答案 1 :(得分:1)

p中的p不允许。创建一个div并在其中添加段落。

https://jsfiddle.net/8fh108cL/

摘录中的相关更改。

<div id="de">
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
</div>
<div id="dd">
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
</div>

答案 2 :(得分:0)

您不应在段落中附加段落。请参阅这篇非常好的帖子from Matt Ball

您的方法是正确的,您可以使用#dd:nth-child(n),其中n是您使用CSS规则定位的孩子。