美文网首页
css中first-child和last-child不生效

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

作者: sxfshdf | 来源:发表于2019-11-04 10:59 被阅读0次
    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

    相关文章

      网友评论

          本文标题:css中first-child和last-child不生效

          本文链接:https://www.haomeiwen.com/subject/snbrbctx.html