我正在尝试将第二个文本 block 设置为具有不同的背景颜色,但它们不是直接的子项。如果不使用 jQuery,这仍然可行吗?
.wrapper .text-block:nth-child(2) {
background-color: red;
}
<div class="wrapper">
<div class="text-block">text-block</div>
<div class="heading">heading</div>
<div class="text-block">text-block</div>
</div>
抱歉,为了更清楚,我希望 text-block
div 在第二个元素上有不同的背景。它们是上面代码片段中显示的 wrapper
div 的子项。
最佳答案
I would like the text-block divs to have a different background on the 2nd element. They are children of the wrapper div shown in the code snippet above.
实现此目的最可靠的方法是不使用 <div>
一切的元素。你的.heading
类意味着 <div>
是标题,所以不是 <div>
你可以使用 <header>
元素代替:
<div class="wrapper">
<div class="text-block">text-block</div>
<header>heading</header>
<div class="text-block">text-block</div>
</div>
现在,选择您的第二个 .text-block
元素,你只需要使用 :nth-of-type
选择器:
.wrapper .text-block:nth-of-type(2) {
background-color: red;
}
.wrapper .text-block:nth-of-type(2) {
background-color: red;
}
<div class="wrapper">
<div class="text-block">text-block</div>
<header>heading</header>
<div class="text-block">text-block</div>
</div>
关于html - 第 n 个 child ,其中 div 不是直接的 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40637713/