<th>元素:hover伪类无法触发?替换为div/section可正常生效
问题描述
我有一个带多个<th>表头的表格,想实现鼠标悬停在#heading这个<th>上时,修改#box1元素的样式。但把<th>换成div或section时功能正常,为啥用<th>就不行?
代码示例
CSS
#heading { text-decoration: none; } #box1 { display: block; background-color: red; width: 100px; height: 100px; } #heading:hover + #box1 { display: block; background-color: blue; width: 50px; height: 50px; }
HTML
<table id="main-players-container"> <tr id="headings"> <th id="heading">Name</th> <th>Price</th> </tr> </table> <div id="box1"> <p>box to change css</p> </div>
原因分析
核心问题在于你用的CSS相邻兄弟选择器(+)的工作逻辑:
- 这个选择器只能匹配同一个父元素下,紧挨着当前元素的下一个兄弟。
- 你代码里的
<th id="heading">,父元素是<tr>,它的直接相邻兄弟是同一行里的另一个<th>;而#box1是<table>的兄弟元素,和<th>根本不在同一个层级,所以<th>的+选择器根本找不到#box1。 - 换成
div或section时,这些标签和#box1是同级的直接相邻元素,选择器自然能生效。
修复方案
要实现需求,得把触发样式变化的选择器层级调整到和#box1同级的元素上,比如用表格的:has()选择器(主流浏览器已支持),精准匹配鼠标悬停在#heading时的情况:
#main-players-container:has(#heading:hover) + #box1 { display: block; background-color: blue; width: 50px; height: 50px; }
如果需要兼容不支持:has()的旧浏览器,也可以退而求其次,让鼠标悬停在整个表格时触发样式变化:
#main-players-container:hover + #box1 { display: block; background-color: blue; width: 50px; height: 50px; }
不过这种方式会导致鼠标碰表格任何地方都改变#box1样式,不如:has()精准。
内容的提问来源于stack exchange,提问作者logan_9997
相关产品推荐
相关产品推荐

