css hover over a div and another div changes opacity

54 Views Asked by At

I'm trying to use CSS in my WordPress site to change the opacity of a div column on the hover of adjacent div column.

This is the CSS I'm using but it's not working. I want to hover over the dog box and have the cat box change to half transparency.

.dog_box {
    height: 200px;
        width: 200px;
    background-color: #000000;
    float:left;
}

.cat_box {
    height: 200px;
    width: 200px;
    background-color: red;
    float:left;
}

.dog_box:hover .cat_box{
    opacity:0.5;
}
<div class="dog_box"></div><div class="cat_box"></div>

This is my site link. I'm not sure what I'm doing wrong. https://parapetcarestg.wpenginepowered.com/home2/

3

There are 3 best solutions below

0
j08691 On

As I said in my comment, your selector is searching for a descendant. You want to use a sibling selector like ~ (general) or + (adjacent)

.dog_box {
    height: 200px;
        width: 200px;
    background-color: #000000;
    float:left;
}

.cat_box {
    height: 200px;
    width: 200px;
    background-color: red;
    float:left;
}

.dog_box:hover + .cat_box{
    opacity:0.5;
}
<div class="dog_box"></div><div class="cat_box"></div>

1
jonas crevecoeur On

The current code, changes the opacity of all cat_box elements inside the dog_box.

In this example you want to use the subsequent-sibling combinator (~) to change the css of all cat_box elements that are at the same level as the dog_box, but appear later on the page.

.dog_box:hover ~.cat_box{
    opacity: .5;
}
0
beaner2880 On

Just in case anyone else was searching for the previous sibling css this worked (I think it might not be supported by firefox though)

.dog_box:hover + .cat_box {
    opacity: 0.7;
}


.dog_box:has(~ .cat_box:hover){
    opacity: 0.7;
}


.dog_box {
    height: 200px;
        width: 200px;
    background-color: #000000;
    float:left;
}

.cat_box {
    height: 200px;
    width: 200px;
    background-color: red;
    float:left;
}
<div class="dog_box"></div><div class="cat_box"></div>