html - 第 n 个 child ,其中 div 不是直接的 child

标签 html css css-selectors

我正在尝试将第二个文本 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/

相关文章:

html - 如何在屏幕太小时隐藏侧边栏?无框架

css - 使用 :checked to toggle CSS for an element anywhere on the page?

javascript - Script 标签将 Javascript 呈现为具有看似有效的 HTML 的文本

html - Safari 8 label + checkbox hover 闪烁,如何防止?

angularjs - 如何在没有 jquery 的情况下使用 title 属性创建自定义工具提示

css - 像乐谱一样灵活的图像缩放/拉伸(stretch)

jquery - 查看父项是否为复选框

javascript - document.querySelector 中允许使用哪些字符?

html - CSS定位问题

javascript - 以专辑封面为背景图像的音频播放器