Home > Enterprise >  hover actions with multiple divs
hover actions with multiple divs

Time:08-05

is there a way to trigger an action on a div, if the hover occurred on another one, and the divs are not inside each other; something like this:

example:

<div ></div>
<div ></div>

css:

.blockA {
    width: 64px;
    height: 64px;
    background-color: red;
}

.blockB {
    width: 64px;
    height: 64px;
    background-color: orange;
    transition: 0.5s ease-out 100ms;
}

.blockA:hover .blockB {
    background-color: blue;
}

it only seems to work for me if the divs are inside each other, otherwise nothing happens

CodePudding user response:

You can only do this if the element you want affected is preceded by the hovered element. In this case, if you want element .blockB to be affected by the hover of .blockA, you can use the general ~ or next element selector. However, if you want .blockA to be affected by the hover on .blockB you need to use Javascript, since there is not a preceding element selector in CSS

.blockA {
    width: 64px;
    height: 64px;
    background-color: red;
}

.blockB {
    width: 64px;
    height: 64px;
    background-color: orange;
    transition: 0.5s ease-out 100ms;
}

/* General Sibling Selector */
.blockA:hover ~ .blockB {
    background-color: blue;
}

.blockC {
    width: 64px;
    height: 64px;
    background-color: red;
}

.blockD {
    width: 64px;
    height: 64px;
    background-color: orange;
    transition: 0.5s ease-out 100ms;
}

/* Next element selector */
.blockC:hover   .blockD {
    background-color: blue;
}
<div ></div>
<div ></div>

<div ></div>
<div ></div>

CodePudding user response:

Add a comma between .blockA:hover .blockB like so:

.blockA:hover, .blockB {
    background-color: blue;
}

Also, I think you want to use .blockB:hover in that case. What happens when there's no comma is that it checks when .blockA is hovered and if so it applies background-color: blue to all elements inside it that have .blockB

  • Related