<th> 元素不会在 :悬停时激活



我有一个在th标记内有多个头的表,当我将鼠标悬停在#heading元素上时,我希望能够更改要显示的另一个元素#box1。将th标记替换为divsection标记时,此操作有效。为什么它不适用于th标签?

#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;
}
<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>

如果你看看浏览器是如何呈现HTML的,你会发现div不是表结构的一部分,而是在表外呈现的,所以相邻的兄弟组合子(+(将无法工作,因为div不再是th元素的兄弟


编辑后在下方添加以下注释

这可以通过将整个部分封装在div中并使用如下所示的:has伪类来实现。注意:has((还没有完全支持(详情请访问caniuse.com(

#heading {
text-decoration: none;
cursor: pointer;
}
#box1 {
display: block;
background-color: red;
width: 100px;
height: 100px;
}
.container:has(#heading:hover) #box1 {
background-color: blue;
width: 50px;
height: 50px;
}
<div class='container'>
<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>
</div>

最新更新