DEV Community

Cover image for Styling siblings on hover in CSS
Sebastiano Guerriero for CodyHouse

Posted on

Styling siblings on hover in CSS

Normally, you would need JavaScript to stylize all the siblings of an element you're interacting with. But wait! There's a cool method based 100% on CSS.

The idea, in short, is to target the :hover of the parent, then target all the children except the one you're hovering over.

.parent:hover .child:not(:hover) {
  /* this style affects all the children except the one you're hovering over */
}

Here's an example:

Originally published at CodyHouse.co

Top comments (5)

Collapse
 
discopigeon profile image
Cedric Garcia

This is so great! I am trying to apply a CSS color change on the siblings of a list of links under the following format:

  <h2 class="list-items">
     <a class="item" href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
  </h2>

Enter fullscreen mode Exit fullscreen mode

The goal being to have all the links in black and when hovering, the one being overed remains black while the rest changes to lightgray.

I unfortunately haven't been able to apply the desired effect with the following CSS:

.item {
  color: black;
  transition: color 0.3s ease;
}

.list-item a:hover.item:not(:hover) {
  color: lightgray;
}
Enter fullscreen mode Exit fullscreen mode

Any clue what I'm missing?

Collapse
 
harry_copper24 profile image
Harry

TO: Sebastiano Guerriero(@guerriero_se) Great article. Great solution. Very clear. Thank you!

RE: Cedric Garcia(@discopigeon) Cedric, you are missing:
(1) The letter "s" in .list-items in your style.
(2) Also, you need to do the hover on the parent .list-items, not on the < a> like this:



  .item {
    color: black;
    transition: color 0.3s ease;
  }

  .list-items:hover a.item:not(:hover) {
    color: lightgray;
  }


Enter fullscreen mode Exit fullscreen mode

Also, here is another way to do the same with a different starting color (: red):



.item {
    /*  Setting all links red to start.  */
    color: red;
    transition: color 0.3s ease;
}

.list-items:hover {
    /*  On hover of parent (.list-items) set selected child (.item) to black  */
    .item {
        color:black;
    }

    /* On hover of parent (.list-item) child (.item) not-selected set to lightgray  */
    .item:not(:hover) {
        color: lightgray;
    }
}


Enter fullscreen mode Exit fullscreen mode
Collapse
 
bayuangora profile image
Bayu Angora

This is great for menu on header and footer.

Collapse
 
guerriero_se profile image
Sebastiano Guerriero

indeed it is :)

Collapse
 
steveplays profile image
Steveplays

Thanks a lot, really nice solution.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.