Search code examples
csscss-selectors

Style child element when hover on parent


How to change the style of child element when there is hover on parent element. I would prefer a CSS solution for this if possible. Is there any solution possible through :hover CSS selectors. Actually I need to change color of options bar inside a panel when there is an hover on the panel.

Looking to support all major browsers.


Solution

  • Yes, you can definitely do this:

    .parent:hover .child {
       /* ... */
    }
    

    This uses the :hover pseudoclass to restrict to elements matching .parent which are also hovered, and the descendant combinator (space) to select any descendant that matches .child.

    Here's a live example:

    .parent {
      border: 1px dashed gray;
      padding: 0.5em;
      display: inline-block;
    }
    
    .child {
      border: 1px solid brown;
      margin: 1em;
      padding: 0.5em;
      transition: all 0.5s;
    }
    
    .parent:hover .child {
      background: #cef;
      transform: scale(1.5) rotate(3deg);
      border: 5px inset brown;
    }
    <div class="parent">
      parent
      <div class="child">
        child
      </div>
    </div>