CSS条件选择器:has()和:nth-last-child()

列表有时候需要根据个数显示不同的样式,这时候,CSS条件选择器能帮上大忙!
主要利用CSS伪类:has():nth-last-child()

:nth-last-child()

<ul>
	<li></li>
	<li></li>
	<li></li>
	<li></li>
	<li></li>
</ul>

li:nth-last-child(n + 3) {
	/*style*/
}

选择倒数第三个,总数必须大于3。

这时候,我们可以设置li大于3时的样式

li:nth-last-child(n + 3),
li:nth-last-child(n + 3) ~ li {
	/*style*/
}
// ~ li : 选择其他的兄弟

minmax()

用CSS gridminmax(),我们还可以设置列表的最小宽度

.list {
	--item-size: 200px; // 默认宽度
	display: grid;
	grid-template-columns: repeat(auto-fit, minmax(var(--item-size), 1fr));
	gap: 1rem;
}

// 当列表个数大于时,改变列表宽度为150px
.list:has(li:nth-last-child(n+5)) {
	--item-size: 150px;
}

动态改变页面头部布局

利用:has:nth-last-child可以检测列表项目是否大于4,然后改变头部布局。
order属性可以改变项目的位置顺序。

.site-header:has(li:nth-last-child(n+4)) {
	.site-header__wrapper > * {
		flex: initial;
	}
	.site-header__start {
        order: 2;
    }

    .site-header__middle {
        order: -1;
        text-align: start;
    }

    .site-header__end {
        margin-left: auto;
    }
}

列表个数大于时的样式显示

<div class="layout">
    <article class="card"></article>
    <article class="card"></article>
    <article class="card"></article>
</div>

.layout {
  display: grid;
  grid-gap: 1rem;
}

.card {
    display: flex;
    gap: 1rem;
    align-items: center;
}

.layout:has(.card:nth-last-child(n + 4)) {
	--layout-4: true; // 布局项目为4时的样式
	grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
}
@container style(--layout-4: true) {
	.card {
		flex-direction: column;
	}
	.card__thumb {
		flex:1;
		width: 100%;
		aspect-redio: 4 /3;
	}
}

弹窗有两个按钮和一个按钮样式

.modal__footer {
    display: flex;
    justify-content: center;
    gap: 0.5rem;
}

/* 如果有两个按钮 */
.modal__footer:has(a:nth-last-child(n + 2)) {
    justify-content: flex-end;
}

超过两个用户头像时,用户头像需要叠起来

img:nth-last-child(n+2) ~ img {
    border: 2px solid #fff;
    margin-left: -0.25rem;
    width: 30px;
    height: 30px;
}

上面的代码可以正常工作,但是可以有更好的写法

.post-author:has(img:nth-last-child(n+2)) {
	--multiple-avatars: true;
}

@container style(--multiple-avatars: true) {
    .avatars-list {
        display: flex;
        background-color: #efefef;
        padding: 8px 12px;
        border-radius: 50px;
    }

    img:not(:first-child) {
        border: solid 2px #fff;
        margin-left: -0.25rem;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值