Loading

last-child可能你也会踩的坑

旧文章从语雀迁移过来,原日期为2021-07-14

问题

当时写在写一个列表,列表每一项需要下面加下划线,最后一项不加下划线。第一时间,想到使用 :``last-child 这个伪类来实现。

当时的代码出来的 HTML 片段大致是这样的(省略号代表还有其他元素):

<div class="list-box">
	<div class="list-item">...</div>
  <div class="list-item">...</div>
  <div class="list-item">...</div>
  <!-- 最后两行是由vant的list组件添加的 -->
  <div class="van-list__finished-text">沒有更多數據了</div>
  <div class="van-list__placeholder"></div>
</div>

样式是这样的:

.list-item {
    border-bottom: #eaeaea 1px solid;
}
.list-item:last-child {
    border-bottom: 0;
}

然后一直没搞明白,为啥最后一行的底部还有下划线呢。

思考

于是我查了 last-child 的定义:

:last-child CSS 伪类 代表父元素的最后一个子元素。

这句定义的重点是元素。

然后我得到第一次的推断:只是通过 :list-item 来定位到父元素而已, :list-child 依然会在父元素上去找最后一个子元素

于是我有写了另外一个例子:

<style>
  .list-box {
    width: 200px;
  }

  .list-box .list-item {
    background: red;
    height: 100px;
  }

  .list-box div {
    background: yellow;
    height: 100px;
  }

  .list-box .list-item:last-child {
    background: green;
  }
</style>
<body>
  <div class="list-box">
    <div class="list-item">111</div>
    <div class="list-item">222</div>
    <div class="list-item">333</div>
    <div>沒有更多數據了</div>
  </div>
</body>

结果最后一个 div 并没有变绿,所以证明我得推测是错误的。
image.png
然后我又改变了例子,把最后一个样式修改为:


.list-box div:last-child {
    background: green;
 }

就生效了:
image.png
那就可以得出结论了:
对于样式 selector:last-child ,要想目标元素生效:既要满足 selector 选择器,还要是当前选择器的父元素最后一个元素。
**

posted @ 2022-12-11 22:29  SimonLiang20  阅读(60)  评论(0编辑  收藏  举报