:last-child的使用误区

代码的html结构如下面代码所示

<template>
  <div class="appArea" v-for="item in EAIApps.apps">
    <span>{{ item.title }}</span>
    <div class="apps" v-if="item.hasOwnProperty('children')">
      <div class="item" v-for="child in item.children">
        <center @click="jump(child)">
          <div class="circle">{{ child.title.substring(0, 1) }}</div>
          <center>
            <span class="listItem">{{ child.title }}</span>
          </center>
        </center>
      </div>
      <van-empty description="暂无菜单" v-if="EAIApps.apps.length == 0" />
    </div>
  </div>
  <van-tabbar v-model="active">
    <van-tabbar-item icon="home-o" @click="goToPage('main')"
      >首页</van-tabbar-item
    >
    <van-tabbar-item icon="setting-o" @click="goToPage('settings')"
      >设置</van-tabbar-item
    >
  </van-tabbar>
</template>

我想要给最后一个appArea增加20像素的底部内边距,于是我写了:

.appArea:last-child {
  padding-bottom: 20px;
}

发现没有效果。

经过查阅资料,我了解到.appArea:last-child选择器的意思是选择类名为appArea并且该元素为父节点下最后一个元素。

而该html结构父节点下最后一个元素并不是appArea,所以无效。

解决方法:

改为

.appArea:nth-last-child(2) {
  padding-bottom: 20px;
}

即可,意为选择类名为appArea并且该元素为父节点下倒数第二个元素。

 

posted @ 2022-06-08 11:30  罗毅豪  阅读(48)  评论(0编辑  收藏  举报