<th> element won't activate on :hover

Viewed 45

I have a table with multiple heads inside th tags where I want to be able to change another element #box1 to be shown when hovering over the #heading element. This works when replacing the th tag with div or section tags. Why wont it work with th tags?

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

1 Answers

If you look at how the browser has rendered your HTML, you'll see that it's recognised that the div isn't part of the table structure and will have rendered it outside the table, so the adjacent sibling combinator (+) won't work as the div is no longer a sibling of the th element


Edited to add following comments below

This can be achieved by wrapping the whole section in a div and using the :has pseudo class as below. Note that :has() isn't fully supported yet (see caniuse.com for details)

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

Related