Steve Thompson
Steve Thompson

Reputation: 141

CSS Hover 1 Div Affects Other non-Child Divs

Here is some mock code. Basically I have no control over the table elements ONLY the div's inside the td's. I need to be able to hover over any of the div's in the row and they all hover to the same state. Can this be done?

Fiddle

HTML and CSS:

.one {
  background-color: #0000FF;
  width: 200px;
  height: 30px;
}

.two {
  background-color: #ff0000;
  width: 200px;
  height: 30px;
}

.three {
  background-color: #00FF00;
  width: 200px;
  height: 30px;
}


/*.one:hover, .two:hover, .three:hover {
  background-color: #000;
}*/

.row1:hover {
  background-color: #000;
}
<table>
  <tr>
    <td>
      <div class="row1 one">
      </div>
    </td>
    <td>
      <div class="row1 two">
      </div>
    </td>
    <td>
      <div class="row1 three">
      </div>
    </td>
  </tr>
</table>

Upvotes: 2

Views: 129

Answers (2)

kumarharsh
kumarharsh

Reputation: 19609

I don't think that's possible using just CSS, given that you have no control / access whatsoever to the table or tr above. If you do have some access (or can say for sure that the divs will be wrapped in a tr, try this code:

(basically, put a rule on the grandfather tr)

tr:hover > td > div {
  background-color: black;
}

https://jsfiddle.net/zbqzu21r/


Weird idea:

You have the parent tr which you cannot control. Try making a table and nesting it inside the td. I'm assuming you can easily control anything done on this table. So, put your selectors on this table, and be done with it.

.mytable:hover tr > td > .row1 {
  background-color: black;
}
<tr>
  <td>
    <table class="mytable">
      <tr>
        <td>
          <div class="row1 one">
          </div>
        </td>
      </tr>
      <tr>
        <td>
          <div class="row1 two">
          </div>
        </td>
      </tr>
      <tr>
        <td>
          <div class="row1 three">
          </div>
        </td>
      </tr>
    </table>
  </td>
</tr>

Upvotes: 1

Oriol
Oriol

Reputation: 288010

In CSS there is no parent selector yet. Therefore, you can't do this directly.

However, you can try using :hover on the nearest common ancestor:

tr:hover .row1 {
  background-color: #000;
}

.one {
  background-color: #0000FF;
  width: 200px;
  height: 30px;
}
.two {
  background-color: #ff0000;
  width: 200px;
  height: 30px;
}
.three {
  background-color: #00FF00;
  width: 200px;
  height: 30px;
}
tr:hover .row1 {
  background-color: #000;
}
<table>
  <tr>
    <td>
      <div class="row1 one"></div>
    </td>
    <td>
      <div class="row1 two"></div>
    </td>
    <td>
      <div class="row1 three"></div>
    </td>
  </tr>
</table>

Note it's not exactly the same: if you hover the border between two cells, they will change color even if you aren't hovering any .row1.

Upvotes: 4

Related Questions