css选择器选择父元素下子元素仅有一个指定 class 的时候

发布时间 2023-05-30 17:28:32作者: 蓓蕾心晴

对于仅指定一个 class 的场景,我们通常会想到使用 :last-child  或者 :only-child 

但是亲测发现,这些伪类选择器不是仅在子元素只有一个我们想要筛选的 class 类的时候,才会被选择,而是仅有一个子元素的时候才会被选中,所以,如果我们子元素还有其他非该类的子元素,则不会被认为是一个,不会被以上伪类选择器选中。

例如:

 

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .btn-group {
      background-color: aqua;
      display: flex;
    }

    .btn-group .btn {
      margin-right: 20px;
    }

    /* .btn-group .btn:only-child {
      margin-right: 0;
    } */
    .btn-group .btn:last-child {
      margin-right: 0;
    }
  </style>
</head>

<body>
  <div class="btn-group">
    <div class="btn">btn1</div>
    <div>其他子元素</div>
  </div>
</body>

</html>

所以解决方案,就是要保证子元素类型相同,否则非想要选择的 class 类的子元素也会算一个 child,或者我们可以给要设置仅一个class 场景的样式的时候,再给相同 class 的子元素包一层 div 即可。