我需要选择一个特定的 HTML 元素,它们是相同的,也包含在几个相同的 div
中,我尝试使用 nth-child()
但它没有不行。 (每个 child 共享相同的属性,但有细微的变化)
HTML
<div class="disc">
<div class="disc_PF">
</div>
</div>
<div class="disc">
<div class="disc_PF">
</div>
<div class="disc_PF">
</div>
</div>
CSS
.disc .disc_PF:nth-child(1) {}
当我使用它时,它会选择第一个 disc_PF
元素,
CSS
.disc .disc_PF:nth-child(2) {}
当我使用它时,它会选择第三个 disc_PF
元素,
如何单独选择单个嵌套元素?
谢谢
最佳答案
这是您可以做到的。
.disc_PF
{
width: 50px;
height: 50px;
}
/* First .disc, all .disc_PF */
.disc:nth-of-type(1) > .disc_PF
{
background: red;
}
/* Second .disc, first .disc_PF */
.disc:nth-of-type(2) > .disc_PF:first-child
{
background: green;
}
/* Second .disc, .disc_PF that is the second child element */
.disc:nth-of-type(2) > .disc_PF:nth-child(2)
{
background: yellow;
}
/* Second .disc, last .disc_PF */
.disc:nth-of-type(2) > .disc_PF:last-child
{
background: blue;
}
<div class="disc">
<div class="disc_PF">
</div>
</div>
<div class="disc">
<div class="disc_PF">
</div>
<div class="disc_PF">
</div>
<div class="disc_PF">
</div>
</div>
关于css - 如何从相同的嵌套 div 中选择特定的 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42310847/