最后一个孩子/最后一个类型的名字不适用于div

时间:2019-10-30 12:53:14

标签: html css css-selectors

我正在尝试更改最后一个div的颜色。 last-childlast-of-type都不起作用。我的代码:

.blue-back {
  background-color:blue;
}

.blue-back:last-of-type {
  background-color:red;
}

.blue-back:last-child {
  background-color:red;
}
    <div class="row">
      <div class="col-md-4">
        <div class="blue-back">
          <p class="mb-0 text-center text-white">Fase</p>
          <p style="font-size:29px; font-weight:600;" class="mb-0 text-center text-white font-weight-600">1</p>
        </div>
      </div>
      <div class="col-md-4">
        <div class="blue-back">
          <p class="mb-0 text-center text-white">Fase</p>
          <p style="font-size:29px; font-weight:600;" class="mb-0 text-center text-white font-weight-600">1</p>
        </div>
      </div>
      <div class="col-md-4">
        <div class="blue-back">
          <p class="mb-0 text-center text-white">Fase</p>
          <p style="font-size:29px; font-weight:600;" class="mb-0 text-center text-white font-weight-600">1</p>
        </div>
      </div>
    </div>

2 个答案:

答案 0 :(得分:3)

这是因为.blue-back的最后一个子项始终是当前项。您需要这样做:

.col-md-4:last-child .blue-back {
    background-color:red;
}

在此处查看CodePen演示:https://codepen.io/ryan_pixelers/pen/KKKXBaz

答案 1 :(得分:1)

您需要使用:last-child选择器来选择.row父级的.col-md-4子级。

因此您可以使用:

.row .col-md-4:last-child .blue-back {
  background-color: red;
}

.row > div:last-child .blue-back {
  background-color: red;
}

.blue-back {
  background-color: blue;
}

.row .col-md-4:last-child .blue-back {
  background-color: red;
}
    <div class="row">
      <div class="col-md-4">
        <div class="blue-back">
          <p class="mb-0 text-center text-white">Fase</p>
          <p style="font-size:29px; font-weight:600;" class="mb-0 text-center text-white font-weight-600">1</p>
        </div>
      </div>
      <div class="col-md-4">
        <div class="blue-back">
          <p class="mb-0 text-center text-white">Fase</p>
          <p style="font-size:29px; font-weight:600;" class="mb-0 text-center text-white font-weight-600">1</p>
        </div>
      </div>
      <div class="col-md-4">
        <div class="blue-back">
          <p class="mb-0 text-center text-white">Fase</p>
          <p style="font-size:29px; font-weight:600;" class="mb-0 text-center text-white font-weight-600">1</p>
        </div>
      </div>
    </div>