使用CSS column-count属性时如何为多列设置交替的红白背景色
实现方案
方案1:ul添加线性渐变背景(最简单,无li数量依赖)
直接给列表容器添加等分的横向渐变背景,刚好匹配4列的宽度划分,无需修改li样式:
.list { column-count: 4; padding: 0; margin: 0; /* 红白交替列背景,4列每列占25%宽度 */ background: linear-gradient( to right, #f55 25%, #fff 25%, #fff 50%, #f55 50%, #f55 75%, #fff 75% ); } /* 可选:调整li样式让展示效果更好 */ .list li { list-style: none; padding: 6px 12px; }
如果设置了column-gap列间距,只需要对应调整渐变的颜色停止点百分比即可适配。
方案2:li匹配nth-child规则(适配动态li数量、列高不一致场景)
利用4列布局的元素排序规律,直接匹配每一列的所有li元素设置背景:
.list { column-count: 4; padding: 0; margin: 0; } .list li { list-style: none; padding: 6px 12px; } /* 匹配第1、3列所有li,设置红色背景 */ .list li:nth-child(4n + 1), .list li:nth-child(4n + 3) { background-color: #f55; } /* 匹配第2、4列所有li,设置白色背景,默认背景为白可省略 */ .list li:nth-child(4n + 2), .list li:nth-child(4n + 4) { background-color: #fff; }
4列布局下每4个li为一行,4n+1对应所有第一列的元素,4n+2对应第二列,以此类推,不管li总数多少都可以正常匹配。
内容的提问来源于stack exchange,提问作者user17234701
相关产品推荐
相关产品推荐

