html - 使用 CSS3 :nth-child() Selector

标签 html css

<分区>


这个问题是由于错别字或无法再重现的问题引起的。虽然类似的问题可能是on-topic在这里,这个问题的解决方式不太可能帮助 future 的读者。

关闭 8 年前

我的 CSS/HTML 在这里:

    p:nth-child(2) {
        background: #ff0000;
    }
<h1>This is a heading</h1>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>

结果在 <p>The first paragraph.</p> 行显示红色

为什么?我认为它必须显示红色 <p>The second paragraph.</p> .

最佳答案

nth-child() 选择特定元素,如果它是父元素的第 n 个(在你的例子中是第 2 个)子元素。

在这里你需要使用 nth-of-type() 来选择元素类型(假设是 p),如果它是其父元素类型的第 n 个(在你的例子中是第 2 个)

p:nth-of-type(2) {
  background: red;
}
<h1>This is a heading</h1>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>

关于html - 使用 CSS3 :nth-child() Selector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27689335/

上一篇:css - 如何制作对 Angular 线div

下一篇:html - 具有固定比例的 CSS 可拉伸(stretch)背景

相关文章:

javascript - 带有垂直文本的 CSS 垂直按钮

html - 背景图片居中,在所有浏览器中都是 100%

html - 手机上不显示图像但仍在加载?

html - 悬停时CSS背景位置变化

javascript - Wordpress 图像选择器 - 在主题选项页面中使用

html - 如何使文本在导航栏中居中对齐

html - 为什么网页在不同的文件夹中显示不同?

Windows 8.1 上 IE11 的 HTML 文本字段大小

html - 如何在 ASP.Net MVC 中使用不同的 Bootstrap 主题?

javascript - 将div放在同一行