在子元素上使用":not(:last-child)"不会跳过真正的最后一个元素

  • 本文关键字:元素 最后一个 not last-child css
  • 更新时间 :
  • 英文 :


如果在同一父元素中不仅存在同一类,则在子元素上使用:not(:last-child)不会跳过真正的最后一个元素。

示例显示,事件Imargin-bottom: 5px赋予除最后一个.blue元素之外的所有.blue元素,最后一个.blue元素仍然具有margin-bottom: 5px样式。

任何人都知道我应该如何做到这一点,或者提供一份文件来解释我应该如何避免这种情况。提前谢谢。

.blue,
.red {
background-color: #ccc;
padding: 5px;
}
.blue {
color: blue;
}
.red {
color: red;
}
.blue:not(:last-child) {
margin-bottom: 5px;
}
<div class="box">
<div class="blue">first blue text</div>
<div class="blue">blue text2</div>
<div class="blue">blue text3</div>
<div class="blue">blue text4</div>
<div class="blue">last blue text</div>
<div class="red">red text</div>
<div class="red">red text</div>
</div>

来自MDN:

:last子CSS伪类表示一组同级元素中的最后一个元素。

它不引用特定类的最后一个。选择器.blue:not(:last-child)匹配.blue的所有元素,而不是.box封装的NodeList中的最后一个子元素。在您的示例中,last-child表示第二个.red元素。

实际上不可能通过特定类或选择器的最后一个进行选择。最接近的是last-of-type,顾名思义,它将选择特定元素类型的最后一个。例如:

h2:last-of-type {
color: red;
}
<h2>First Heading</h2>
<h2>Second Heading</h2>
<p>Paragraph 1</p>
<p>Paragraph 2</p>

:last子CSS伪类表示一组同级元素中的最后一个元素Ref

没有"类的最后一个">选择器已存在。。。针对该元素的唯一方法是向其添加一个特定的类

您可以使用JavaScript来完成它,而不是在标记中手动完成:

let all_blue = document.querySelectorAll(".blue");
Array.from(all_blue).slice(-1)[0].classList.add("last-blue");
.blue,
.red {
background-color: #ccc;
padding: 5px;
}
.blue {
color: blue;
}
.red {
color: red;
}
.blue:not(.last-blue) { /* .last-blue is used here */
margin-bottom: 5px;
}
<div class="box">
<div class="blue">first blue text</div>
<div class="blue">blue text2</div>
<div class="blue">blue text3</div>
<div class="blue">blue text4</div>
<div class="blue">last blue text</div>
<div class="red">red text</div>
<div class="red">red text</div>
</div>

相关内容

最新更新