为表格行标题与列标题添加边框样式的技术求助
解决方案
针对你的两个表格样式需求,我们可以通过CSS的:has()伪类和否定选择器精准匹配表格类型,实现对应的边框效果:
修改后的完整CSS代码
table { overflow-x:auto; border-collapse: collapse; margin: 1.5rem 0 2.5rem 0; width: 100% !important; caption-side: bottom; border-color: transparent; } td { text-align: left; vertical-align: top; padding: 10px 12px !important; border-bottom: 0.1rem solid #8A959E; vertical-align: text-top; } td ul li { margin-bottom: 0 !important; } td ol li { margin-bottom: 0 !important; } td ul li::marker { font-size: 1.2rem !important; color: #2d3b45 !important; } td ol li::marker { font-size: 1rem !important; color: #2d3b45 !important; } th { border-bottom: 0.1rem solid #8A959E; padding: 16px 12px !important; vertical-align: text-top; text-align: left; font-weight: 800; } th[scope=col] { vertical-align: bottom; padding: 16px 16px 8px 16px !important; } /* 需求1:为表头行(scope=col)的第一行底部添加粗蓝色边框 */ tbody tr:first-child:has(th[scope=col]) th { border-bottom: 0.2rem solid #2774ae; } /* 需求2:仅当表格只有表头列(scope=row)时,为第一行顶部添加粗蓝色边框 */ table:not(:has(th[scope=col])) tbody tr:first-child th, table:not(:has(th[scope=col])) tbody tr:first-child td { border-top: 0.2rem solid #2774ae; } tbody tr:nth-child(even) { background-color: #f4f4f4; } th:first-child, td:first-child { padding-left: 1rem !important; } th:last-child, td:last-child { padding-right: 1.5rem !important; } caption { text-align: left; margin: 0.5rem 0; color: #595959; font-style: italic; padding: 0 15px !important; }
关键修改说明
- 移除原错误规则:删掉了
th:first-child规则,它会不分场景给所有表格的第一个表头单元格加下边框,不符合需求。 - 表头行专属样式:通过
tbody tr:first-child:has(th[scope=col]) th匹配包含列表头的第一行,给该行所有表头单元格添加粗蓝色下边框,实现示例1的效果。 - 表头列专属样式:用
table:not(:has(th[scope=col]))筛选出没有列表头的表格,给这类表格第一行的所有单元格(行表头+数据单元格)添加粗蓝色上边框,实现示例2的效果。
内容的提问来源于stack exchange,提问作者VeeSands
相关产品推荐
相关产品推荐

