我有这个 HTML:
<div class="homepage-body">
<a href="#">
<div class="homepage-item">
<div class="homepage-icon"></div>
<div class="homepage-text">
Test1
</div>
</div></a> <a href="#">
<div class="homepage-item">
<div class="homepage-icon"></div>
<div class="homepage-text">
Test2
</div>
</div></a> <a href="#">
<div class="homepage-item">
<div class="homepage-icon"></div>
<div class="homepage-text">
Test3
</div>
</div></a> <a href="#">
<div class="homepage-item">
<div class="homepage-icon"></div>
<div class="homepage-text highlighted">
Test4
</div>
</div></a>
</div>
我正在尝试使用不同的 CSS 定位 4 个 homepage-item
div 中的每一个。我尝试使用 nth-child
或 nth-of-type
,而不是为每个 homepage-item
实例添加单独的类。
我尝试了不同的 CSS 组合,但它能做的最好的事情是将第一 (1) 个 CSS 应用于所有四个 homepage-item
div:
.homepage-body > a > div:nth-of-type(1) {
background: green;
}
.homepage-body > a > div:nth-of-type(2) {
background: red;
}
.homepage-body > a > div:nth-of-type(3) {
background: yellow;
}
.homepage-body > a > div:nth-of-type(4) {
background: blue;
}
最佳答案
改成这个
.homepage-body > a:nth-of-type(1) > div {
background: green;
}
旁注:
如果您缩进代码,您也会看得更清楚
<div class="homepage-body">
<a href="#">
<div class="homepage-item">
<div class="homepage-icon"></div>
<div class="homepage-text">
Test1
</div>
</div>
</a>
...
</div>
关于html - 选择包裹在另一个元素中的第 nth-child 或 nth-of-type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36431896/