css中first-child和last-child不生效

html 代码
<div class = "user-wrapper">
  <a-avatar :src=userInfo.url
            v-if="userInfo.url" />
  <a-avatar v-else
            style="backgroundColor:#87d068" icon="user" />
  <a-button type="link"
            v-if="!hasUserInfos()"
            @click="login">登录</a-button>
  <div class="userinfo-item"
       v-for="(item, index) in userInfo.infos"
       :key="index">
    <span class="item-title">{{item.title}}:</span>
    <span class="item-content">{{item.content}}</span>
  </div>
  <a-icon class="trigger"
          v-if="hasUserInfos()"
          @click="logout"
          type="logout" />
</div>
css 代码
.user-wrapper {
    display: flex;
    align-items: center;

    .userinfo-item {
        margin-left: 16px;

    &:first-child {
        border: 1px solid red
    }
    
    &:last-child: {
        border: 1px solid red;
    }
}

发现 last-child 和 first child 中的样式不生效。然后把 html 中 class 为 userinfo-item 的 div 前后的元素都去掉,last-child 和 first-child 样式才生效。

当时实际使用中还是需要 div 前后的元素,此时把 first-child 和 last-child 分别改成 first-of-type 和 last-of-type 即可,样式都正常生效。

css代码
.user-wrapper {
    display: flex;
    align-items: center;

    .userinfo-item {
        margin-left: 16px;

    &:first-of-type {
        border: 1px solid red
    }
    
    &:last-of-type: {
        border: 1px solid red;
    }
}
first-child 和 first-of-type 区别:

first-child:指的是父元素的第一个元素,在上面的例子中,要实现样式的话需要保证 class 为 userinfo-item 的 div 元素没有兄弟元素,或者在创建一个单独 div 包裹起来;

first-of-type:指的是父元素下,相同类型子元素中的第一个,上面的例子中因为 class 为 userinfo-item 的 div 元素是第一个 div 元素,所以生效了,此时如果前面有其他 div 元素,则样式还是不生效的;

last-child 和 last-of-type 原理类似。

first-of-type mdn:https://developer.mozilla.org/zh-CN/docs/Web/CSS/:first-of-type

first-child mdn:https://developer.mozilla.org/zh-CN/docs/Web/CSS/:first-child

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 其实平时用得多的选择器无非也就是那么几个,时间久了,许多不常用的选择器就慢慢忘记了。为了不让自己忘记这些选择器,今...
    盛夏晚清风阅读 1,874评论 0 5
  • CSS 是什么 css(Cascading Style Sheets),层叠样式表,选择器{属性:值;属性:值}h...
    崔敏嫣阅读 1,508评论 0 5
  • 一:在制作一个Web应用或Web站点的过程中,你是如何考虑他的UI、安全性、高性能、SEO、可维护性以及技术因素的...
    Arno_z阅读 1,212评论 0 1
  • class 和 id 的使用场景? class写专门的class通用和私有模块命名,id具有唯一性且优先级太高,用...
    好好顽阅读 419评论 0 0
  • 虽然是个编辑,但是自从上班之后就很少写文章了,因为约稿的缘故,认识了几个大咖,某个是知音的编辑,专业情感记者三十年...
    伊尔呦阅读 144评论 0 0