EdwardBlack EdwardBlack - 1 month ago 7
CSS Question

Change style of multiple specific elements on hover at a specific element

How can I change the style of different elements on hover at a specific element?

E.g. there are multiple divs, and you want to change the style of some of them to unique individual styles, if the mouse hovers over a specific div.



.standard {
background-color: #D8D8D8;
border: 1px solid black;
height:60px;
width:60px;
margin:4px;
}

<div class="standard" id="master"><center>HOVER HERE</center></div>
<div class="standard" id="element"><center>1</center></div>
<div class="standard" id="another_element"><center>2</center></div>
<div class="standard yet_another_element"><center>3</center></div>





Please run the example.
How can I change different style attributes of
another_element
and
yet_another_element
, (e.g. the
background-color
) if the user hovers over the element with id
master
?

Answer

It does only work, if the elements which you try to manipulate, are child elements of the element on which you are hovering (master).

Then you can use CSS code like this to access and manipulate these elements:

By using ID

#master:hover #another_element {
    background-color: orange;
}

By using Class

#master:hover .yet_another_element {
    background-color: red;
}

Example

/* --- By using ID --- */
#master:hover #another_element {
    background-color: orange;
}

/* --- By using Class --- */
#master:hover .yet_another_element {
    background-color: red;
}


/*--- Irrelevant CSS Code...---*/
.standard {
    background-color: #D8D8D8;
    border: 1px solid black;
    height:60px;
    width:60px;
    margin:4px;
    color: white;
    font-weight: 600;
}

#element {
  background-color: green;
}

#master {
  background-color: #fafafa;
}
<div id="master">
    <center>hover here</center>
    <div class="standard" id="element"><center>1</center></div>
    <div class="standard" id="another_element"><center>2</center></div>
    <div class="standard yet_another_element"><center>3</center></div>
</div>