css不是第一个child,css中first-child和last-child不生效

html 代码

v-if="userInfo.url" />

style="backgroundColor:#87d068" icon="user" />

v-if="!hasUserInfos()"

@click="login">登录

v-for="(item, index) in userInfo.infos"

:key="index">

{{item.title}}:

{{item.content}}

v-if="hasUserInfos()"

@click="logout"

type="logout" />

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 原理类似。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值