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

html 代码
登录
{{item.title}}: {{item.content}}
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不生效)