有没有CSS选择器可以选中父容器中最内层的嵌套元素?

前端开发 2026-07-11

在CSS中,是否有办法选取作为父元素div.listCan的子元素中层级最深的那个

    ?在这个例子里,就是包含名为Section 1.2.1.1的列表项的那个

我目前最接近的方法是选取一个没有直接子

这个 回答 对我相关问题的回答非常巧妙,里面可能有适用于这里的解法,但我还没想明白。

谢谢。

.listCan {
  width:fit-content;
  border: 1px solid black;
  padding-right: 30px;
}

div ul:not(:has(li > ul > li > ul)) ul:not(:has(li > ul)) {
  color:red;
}
<div class="listCan">
  <ul>
    <li> Section 1
       <ul>
          <li> Section 1.1 
            <ul>
                <li> Section 1.1.1 </li>
            </ul>
          </li>
          <li> Section 1.2
            <ul>
                <li> Section 1.2.1 
                  <ul>
                    <li> Section 1.2.1.1 </li>
                  </ul>
                </li>
                <li> Section 1.2.2 </li>
            </ul>
         </li>
       </ul>
    </li>
    <li> Section 2
       <ul>
          <li> Section 2.1 
            <ul>
                <li> Section 2.1.1 </li>
            </ul>
          </li>
          <li> Section 2.2
            <ul>
                <li> Section 2.2.1 </li>
                <li> Section 2.2.2 </li>
            </ul>
         </li>
       </ul>
    </li>
</ul>

解决方案

如果你大致知道最大嵌套深度,可以写相应的CSS。或者在SCSS等中生成它。当然,这样做只有在嵌套层级不是很深时才合适。

.listCan {
  width:fit-content;
  border: 1px solid black;
  padding-right: 30px;
}

div{
  ul{
    ul{
       color:red;
    }
    &:has(ul ul){
      ul{
        color: unset;
      }
      ul ul{
         color:red;
      }
    }
    &:has(ul ul ul){
      ul ul{
        color: unset;
      }
      ul ul ul{
         color:red;
      }
    }
    &:has(ul ul ul ul){
      ul ul ul{
        color: unset;
      }
      ul ul ul ul{
         color:red;
      }
    }
    &:has(ul ul ul ul ul){
      ul ul ul ul{
        color: unset;
      }
      ul ul ul ul ul{
         color:red;
      }
    }
  }
}
<div class="listCan">
  <ul>
    <li> Section 1
       <ul>
          <li> Section 1.1 
            <ul>
                <li> Section 1.1.1 </li>
            </ul>
          </li>
          <li> Section 1.2
            <ul>
                <li> Section 1.2.1 
                  <ul>
                    <li> Section 1.2.1.1 </li>
                  </ul>
                </li>
                <li> Section 1.2.2 </li>
            </ul>
         </li>
       </ul>
    </li>
    <li> Section 2
       <ul>
          <li> Section 2.1 
            <ul>
                <li> Section 2.1.1 </li>
            </ul>
          </li>
          <li> Section 2.2
            <ul>
                <li> Section 2.2.1 </li>
                <li> Section 2.2.2
                  <ul>
                    <li> Section 2.2.2.1 </li>
                  </ul>
                </li>
            </ul>
         </li>
       </ul>
    </li>
</ul>
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章