-->

CSS: show style on hover over multiple divs placed

2020-07-28 10:29发布

问题:

I have 2 divs of different dimension placed one over the other. So there is a common intersection area. There is CSS :hover rule set for both the divs. If I hover over each div then the rule applies. But if I move over the intersection area, only the top div hover is actuated.

When the mouse hovers on the area of intersection, I want the :hover rule to actuate for both the divs.

Please see example code at jsfiddle

On hover over the divs, the border shows up in black. I want both the div borders to show up when mouse hovers over the intersection area.

The same code is copy pasted below for reference:

HTML

<div class='lower-layer'></div>
<div class='upper-layer'></div>

CSS

.upper-layer {
  width: 200px;
  height: 100px;
  background-color: red;
  position:absolute;
  left: 20px;
  top: 20px;
}

.lower-layer {
  width: 100px;
  height: 200px;
  background-color: blue;
  position:absolute; 
}

.upper-layer:hover {
  border: solid 2px black;   
}

.lower-layer:hover {
  border: solid 2px black;   
}

UPDATE: To make the question more explicit. I want the border of both the divs to show up only when the mouse is within the green box in the image below

If the mouse is over the black boxes like in image below then only the individual div under the mouse should show its border.

回答1:

Add :hover to your containing div (span) instead of each of the inner divs;

.upper-layer {
    width: 200px;
    height: 100px;
    background-color: red;
    position:absolute;
    left: 20px;
    top: 20px;
}
.lower-layer {
    width: 100px;
    height: 200px;
    background-color: blue;
    position:absolute;
}
span:hover div {
    border: solid 2px black;
}

Here's the Jsfiddle: Double Hover



标签: css hover