CSS tbody使用:not(:first-child)伪类时首个元素被样式命中问题
问题原因
你写的CSS样式命中了所有tbody,核心是:first-child伪类的匹配逻辑和预期不符:
:first-child匹配的是父元素下的第一个子节点,不限制节点类型。
查看HTML结构可以发现,table#general_list的第一个子节点是<thead>标签,排在最前面的tbody.divider是table的第二个子节点,完全不满足:first-child的匹配条件。因此tbody.divider:not(:first-child)规则会命中所有带divider类的tbody,导致所有tbody都被加上红色上边框。
修复方案
任选以下一种写法替换原有CSS规则,即可实现「排除第一个tbody,为其余tbody加自定义样式」的需求:
- 方案1:用
:first-of-type伪类替换:first-child:first-of-type会匹配父元素下同标签类型的第一个节点,正好对应你要选中第一个tbody的需求:
div.cont_table_toggle table#general_list tbody.divider:not(:first-of-type) { border-top: 8px solid red; }
- 方案2:使用通用兄弟选择器
通过~选择器,匹配所有前面存在其他tbody.divider的同类型元素,天然会排除第一个tbody,逻辑更直观:
div.cont_table_toggle table#general_list tbody.divider ~ tbody.divider { border-top: 8px solid red; }
问题原代码
你之前编写的错误规则和对应页面结构如下:
/* 错误写法:第一个tbody不是table的第一个子节点,无法被:first-child匹配 */ div.cont_table_toggle table#general_list tbody.divider:not(:first-child) { border-top: 8px solid red; }
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/> <div class="cont_table_toggle"> <table id="general_list" class="table table-bordered"> <thead> <tr> <th>AAAA</th> <th>BBBB</th> </tr> </thead> <tbody id="block-1" class="divider"> <tr> <td>1111</td><td>2222</td> </tr> </tbody> <tbody id="block-2" class="divider"> <tr> <td>3333</td><td>4444</td> </tr> </tbody> <tbody id="block-3" class="divider"> <tr> <td>5555</td><td>6666</td> </tr> </tbody> </table> </div>
内容的提问来源于stack exchange,提问作者Robert
相关产品推荐
相关产品推荐

