html - 使用 nth-child 将 CSS 样式应用于特定标签甚至在它们之间存在其他标签

标签 html css

我有一个关于 nth-child 选择器的简单问题要问 CSS3 专家(这里我是 extemely n00b)

我有以下简单的 html 代码:

<div>1</div>
<div>2</div>
<div>3</div>
<span>span3</span>
<div>4</div>
<div>5</div>

一个CSS样式:

div:nth-child(2n+1) {
    color: red;
}

div, span {
    float: left;
}

我为你创建了一个 fiddle :http://jsfiddle.net/Q8aPe/

结果是:

123span345 其中 1、3、4 和 5 为红色。

我期望的是:1,3,5 为红色。

为什么? nth-child 不关心标签 child 吗?或者它只是指一个元素(不管标签有什么)?

谢谢

最佳答案

你是对的,nth-child 根据元素在其所有兄弟元素中的位置来决定。您想要的是 nth-of-type,它基于元素在其所有潜在 css 匹配项中的位置。

http://jsfiddle.net/Q8aPe/1/

div:nth-of-type(2n+1) {
    color: red;
}

关于html - 使用 nth-child 将 CSS 样式应用于特定标签甚至在它们之间存在其他标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19861573/

相关文章:

html - flex-basis 与 flex-grow 结合起来到底是如何工作的?

html - IE 9 的 Magic Zoom z-index 问题

javascript - Chart.js V2 格式/样式标签

javascript - 我怎样才能给我的汉堡菜单动画?

html - 在不使用 Javascript 的情况下仅使用 CSS 模拟滚动容器中的 Excel 列锁定

html - Bootstrap 4 : Footer not at bottom

html - float 和媒体查询在 IE 中不起作用

html - 自动调整包含两个元素的 <div> 的高度

html - 使用 1 个 css 类来交换子级的样式

jQuery .each 循环与简单的数学不给出单独的结果