html - 选择包裹在另一个元素中的第 nth-child 或 nth-of-type

标签 html css css-selectors

我有这个 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-childnth-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/

相关文章:

javascript - 通过添加所选日期来更新文本区域

html - 如何强制固定导航栏具有 PAGE 的全宽而不是视口(viewport)?

html - Bootstrap col 随滚动溢出而不是相互堆叠

jquery - React 组件使用 JQuery 查找 last-of-type 类

css - CSS "Quote in a Quote"问题

javascript - 如何在不切换到新标签的情况下在 JavaScript 中打开新标签?

html - 编织多个html文件rstudio

html - 可以在 :focus? 上设置其他元素的样式

html - css hover 只适用于 firefox

javascript - 我正在尝试获取此元素 margin-top 并简单地更改它