html - 第 n 个 child 选择了不正确的元素?

标签 html css css-selectors

我有以下 html:

<body>
<div id="left"></div>
<div id="right"></div>
<div id="top"></div>
<div id="bottom"></div>
<h3 id="fancy">
  This is one fancy heading!
</h3>
<p>
  But I am a very plain paragraph
</p>
<p id="fancy"> But I'm fancy too!
</body>

使用以下 CSS:

body {
  margin-left: 20px;
}

body :nth-child(7) {
font-family: courier;
}

#fancy {
  font-family: Cursive;
}

我想知道当第 n 个 child 被标记为 7 时,css 只将段落的字体更改为 courier。我计算的每一种方式,我只看到它在逻辑上是第 6 个、第 5 个(如果它从 0 开始)甚至可能是第二个 child (如果由于某种原因不计算 div)。谁能给我解释一下“很朴素的段落”怎么是正文的第7个 child ?

最佳答案

第7个 child 是

<p id="fancy"> But I'm fancy too!</p>

(仅供引用,您缺少关闭 </p> 标签)

为了方便看,看这个 JS Fiddle Demo 我在其中添加了 color:red;body :nth-child(7) .

进一步分解

body {
  margin-left: 20px; //this is applied to all of your elements
}

body :nth-child(7) {
  font-family: courier; //this is applied to 7th child
}

#fancy {
  font-family: Cursive; 
  //this is applied to all elements with id="fancy" including the 7th child
  //this overwrites font-family: courier;
}

另外,正如 DJ @Paulie_D 所指出的,不要使用 id每页不止一次。而是使用 class="fancy"在你的 CSS 中 .fancy而不是 #fancy .

关于html - 第 n 个 child 选择了不正确的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25415757/

相关文章:

javascript - 即使 jQuery 中不满足条件也执行 else 语句

javascript - Internet Explorer 视口(viewport)宽度单位错误与 img 标签

jquery - 如何在点击时更改其他列表项的不透明度?

css - IE6 中的链接样式行为

html - 如何均匀地铺开这些卡片

html - 左文本对齐对不同的字母有不同的作用

javascript - 更改单个占位符字符颜色?

javascript - 使用控制台调试 JavaScript

css - 图像上的属性选择器在 IE7 中失败

html - 使用具有多个 id 的 H 选择器时如何缩短 CSS?