自定义表格:nth-child(even)选择器失效问题求助
问题分析与解决方案
你的核心问题是CSS选择器定位错误:
- 原代码
.table:nth-child(even)是选中父元素下的第偶数个.table容器本身,而非容器内的表格行(.tr),所以才会出现父元素被上色的情况。 - 你需要定位到
.table容器内的.tr子元素,再区分奇偶行。
正确的CSS代码修改
根据你的HTML结构(.table内第一个子元素是.thead,后续为.tr行),若要给视觉上的奇数列表行(第1、3个.tr)添加背景色,使用以下选择器:
/* 选中.table下第2、4个子元素,对应视觉上的第1、3行 */ .table .tr:nth-child(even) { background-color: #ff9900; }
若要给视觉上的偶数列表行(第2个.tr)添加背景色,则改为:
.table .tr:nth-child(odd) { background-color: #ff9900; }
额外优化建议
- 移除
.table中无用属性:border-collapse和border-spacing仅对原生<table>标签生效,你的表格是div模拟的,这些属性可以删除。 - 去掉
!important:只要选择器优先级足够(比如.table .tr优先级高于单独的.tr),无需强制覆盖样式。
修改后的完整CSS示例:
.table { width: 100%; color: white; border-radius: 10px; margin-top: 5rem; } .table .tr:nth-child(even) { background-color: #ff9900; } .thead { background-color: red; border-radius: 10px; display: flex; padding: 0 2rem; align-items: center; height: 60px; } .tr { height: 60px; display: flex; align-items: center; padding: 0 2rem; } .th { font-size: 14px; font-weight: 500; text-align: start; flex: 1; } .td { font-size: 11px; text-align: start; flex: 1; color: red; }
内容的提问来源于stack exchange,提问作者Brimstone
相关产品推荐
相关产品推荐

