【问题标题】:Last child / last of type not working on div [duplicate]最后一个孩子/最后一个类型不能在 div 上工作 [重复]
【发布时间】:2019-11-06 20:14:49
【问题描述】:

我正在尝试更改最后一个 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>

【问题讨论】:

  • 您只需要确保父母中确实有孩子。在这种情况下,每个项目只有一个名为 .blue-black 的 last-child

标签: html css css-selectors


【解决方案1】:

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

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

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

【讨论】:

  • 你试过这个并发现它有效吗?
  • 我知道它有效
  • 嗨,我试过了,一切都是蓝色的。红色@RyanMc 没有任何变化
  • 绝对有效codepen.io/ryan_pixelers/pen/KKKXBaz你是不是输入了错误的类名@Gago?
  • 是的,它确实有效。谢啦。 @RyanMc
【解决方案2】:

您需要将: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>

【讨论】:

    猜你喜欢
    • 2017-03-07
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多