我试图理解为什么这个 nth-of-type
选择器没有按预期工作。我的目标是将第一个 .row
元素设为红色,在第一个蓝色元素之后将所有其他元素设为红色,同时让元素保持原样为绿色。
https://jsfiddle.net/darrengates/pa34zyjd/14/
.wrapper div {
width: 200px;
background-color: green;
color: white;
margin: 5px;
padding: 5px;
}
.wrapper .row:nth-of-type(n+1) {
background-color: red;
}
.wrapper .row:nth-of-type(n+2) {
background-color: blue;
}
<div class="wrapper">
<div class="option">option</div>
<div class="button">some button</div>
<div class="row">I wanna be red</div>
<div class="row">I wanna be blue</div>
<div class="row">I wanna be blue</div>
<!-- all other row elements after the first should be blue -->
</div>
最佳答案
n-th-of-type
选择器指的是同一级别的标签类型,不是类,在本例中div
标签是 .wrapper
中的兄弟标签。因此,您需要此 CSS,因为它们是其中的第三个和第四个 div
:
.wrapper .row:nth-of-type(n+3) {
background-color: red;
}
.wrapper .row:nth-of-type(n+4) {
background-color: blue;
}
关于html - nth-of-type css 选择器以类的第一个元素为目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42170661/