Bootstrap两列布局下未知数量div集合的四角边框圆角实现方案
解决方案
可以通过CSS组合选择器实现根据子元素总数的奇偶性自动匹配样式,无需手动切换规则。
实现原理
利用:first-child:nth-last-child(奇偶关键词)组合选择器判断父容器子元素总数:
- 当第一个子元素同时满足
nth-last-child(even)时,说明父容器总共有偶数个子元素 - 当第一个子元素同时满足
nth-last-child(odd)时,说明父容器总共有奇数个子元素
再通过通用兄弟选择器~选中对应位置的子元素应用圆角规则即可。
完整CSS代码
body{margin:10px;} .server{border:1px solid black;color:white;font-weight:bold;padding:10px} /* 顶部圆角固定生效 */ .server:first-child{border-top-left-radius:7px;} .server:nth-child(2){border-top-right-radius:7px;} /* 偶数个元素场景 */ .server:first-child:nth-last-child(even) ~ .server:last-child{border-bottom-right-radius:7px;} .server:first-child:nth-last-child(even) ~ .server:nth-last-child(2){border-bottom-left-radius:7px;} /* 奇数个元素场景 */ .server:first-child:nth-last-child(odd) ~ .server:last-child{border-bottom-left-radius:7px;border-bottom-right-radius:7px;} .server:first-child:nth-last-child(odd) ~ .server:nth-last-child(2){border-bottom-right-radius:7px;}
内容的提问来源于stack exchange,提问作者Phaelax
相关产品推荐
相关产品推荐

