search

Home  >  Q&A  >  body text

How to affect other elements when one element is hovered

<p>What I want to do is when one <code>div</code> is hovered, it affects the properties of another <code>div</code>. </p> <p>For example, in this JSFiddle demo, when you hover over <code>#cube</code> it changes the <code>background-color</code> but I want The thing is, when I hover over <code>#container</code>, <code>#cube</code> is affected. <!-- p--> </p><p><br /></p> <pre class="brush:css;toolbar:false;">div { outline: 1px solid red; } #container { width: 200px; height: 30px; } #cube { width: 30px; height: 100%; background-color: red; } #cube:hover { width: 30px; height: 100%; background-color: blue; }</pre> <pre class="brush:html;toolbar:false;"><div id="container"> <div id="cube"> </div> </div></pre> <p><br /></p>
P粉769413355P粉769413355461 days ago466

reply all(2)I'll reply

  • P粉953231781

    P粉9532317812023-08-28 10:42:01

    In this specific example you can use:

    #container:hover #cube {
        background-color: yellow;   
    }
    

    This example only works if cube is a child of container. For more complex scenarios, you'll need to use different CSS, or use JavaScript.

    reply
    0
  • P粉633733146

    P粉6337331462023-08-28 00:09:44

    If the cube is directly inside the container:

    #container:hover > #cube { background-color: yellow; }
    

    If the cube is located next to the container (after the container's closing tag):

    #container:hover + #cube { background-color: yellow; }
    

    If the cube is located somewhere inside the container:

    #container:hover #cube { background-color: yellow; }
    

    If the cube is a sibling of the container:

    #container:hover ~ #cube { background-color: yellow; }
    

    reply
    0
  • Cancelreply