skip to Main Content

I want to hover any of the div that have the id of symbol and change the color of #bg, how do i do it?

<div id="container">
    <div id="symbol1"></div>
    <div id="symbol2"></div>
    <div id="symbol3"></div>
    <div id="symbol4"></div>
</div>
<div id="bg"></div>

I tried to use this but it didn’t work. I also used + and > and just a space too.

#symbol3:hover ~ #bg{
    background-color:red;
}

but it didn’t work

2

Answers


  1. The issue with the code is that which disinfor has stated.
    If you move the #bg div to be outside but prior to the #container div then you can use the below.
    The :has() selector will select a #bg element that is followed by a #container element of which has a div#symbol3 being hovered.
    If you can not change the structure of the HTML, I believe you would to use some sort of JS.

    #bg:has(+ #container div#symbol3:hover) {
      background-color: red;
    }
    <div id="bg">0</div>
    <div id="container">
      <div id="symbol1">1</div>
      <div id="symbol2">2</div>
      <div id="symbol3">3</div>
      <div id="symbol4">4</div>
    </div>
    Login or Signup to reply.
  2. A quick way to do this is to combine the :has() selector and the target attribute selector [attribute*="value"] which selects any element that has a substring value in its attribute.

    #bg {
      /* just to display #bg div */
      width: 100px;
      height: 100px;
      background-color: black;
    }
    
    #container:has([id*="symbol"]:hover) + #bg {
      background-color: red;
    }
    <div id="container">
      <div id="symbol1">1</div>
      <div id="symbol2">2</div>
      <div id="symbol3">3</div>
      <div id="symbol4">4</div>
    </div>
    <div id="bg"></div>

    #container:has([id*="symbol"]:hover) + #bg means to check for #container that has an id with a value containing symbol while it is being hovered on, then to select the #bg placed immediately after it.

    Read more on CSS selectors: w3schools CSS Selectors Reference

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search