首页 > 解决方案 > 如何在css中选择tspecific类的最后一个孩子

问题描述

需要将 CSS 应用于具有类名的 div ,test但最后一个 div 具有 class test

在以下情况下 - 前 2 个 div.test 应该有边距,但第 3 个 div.test 不应该。

<div class="parent">
   <div class="test">
      <div>The first paragraph.</div>
   </div>
   <div class="test">The second paragraph.</div>
   <div class="test">The third paragraph.</div>
   <div class="test">The fourth paragraph.</div>
   <div class="test-1">The firth paragraph</div>
</div>

div.test-1不应该应用任何东西

标签: htmlcss

解决方案


用于.test:nth-last-child(-n+2)选择的最后一个孩子.test

.test:nth-last-child(-n+2){
color:red;
}
<div class="parent">
   <div class="test">
      <div>The first paragraph.</div>
   </div>
   <div class="test">The second paragraph.</div>
   <div class="test">The third paragraph.</div>
   <div class="test">The fourth paragraph.</div>
   <div class="test-1">The fourth paragraph.</div>
</div>


推荐阅读