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

时间:2016-04-05 16:21:28

标签: 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中的每一个。我没有为homepage-item的每个实例添加单独的类,而是尝试使用nth-childnth-of-type

我尝试过不同的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;
}

1 个答案:

答案 0 :(得分:2)

更改为

.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>
相关问题