j-petty
j-petty

Reputation: 3026

How to style siblings that aren't being hovered?

There's an effect I want to achieve where when a list item is hovered, all other list items are faded out.

I'm looking for a way of applying a style to an element which is not being hovered, when one of it's siblings are hovered.

I've come close with two approaches:

1. Detecting hover on parent

The problem with this is that hovering anywhere in the parent element, even between the anchor tags causes the effect. This isn't desirable, it should only apply the effect when hovering over the actual list item.

.d-flex {
  display: flex;
  justify-content: space-around;
}

.d-flex:hover a:hover {
  color: black;
}

.d-flex:hover a {
  color: white;
}

.d-flex a {
  color: blue;
}
<div class="d-flex">
  <div class="item"><a href="#">item 1</a></div>
  <div class="item"><a href="#">item 2</a></div>
  <div class="item"><a href="#">item 3</a></div>
  <div class="item"><a href="#">item 4</a></div>
</div>

2. Using the ~ operator

This is close but the problem here is that the general sibling combinator only selects siblings which appear after the element in the DOM.

.d-flex {
  display: flex;
  justify-content: space-around;
}

a {
  color: black;
}

.item:hover ~ .item a{
  color: white;
}

a:hover {
  color: blue;
}
<div class="d-flex">
  <div class="item"><a href="#">item 1</a></div>
  <div class="item"><a href="#">item 2</a></div>
  <div class="item"><a href="#">item 3</a></div>
  <div class="item"><a href="#">item 4</a></div>
</div>

PLEASE NOTE: I'm looking for a CSS only solution to this problem. I know it can be achieved with JavaScript, however I'm trying to avoid that approach.

Upvotes: 1

Views: 174

Answers (1)

Temani Afif
Temani Afif

Reputation: 273551

You are almost good with your first method. Simply consider pointer-events to disable the hover on the empty spaces and keep it only on the links:

.d-flex {
  display: flex;
  justify-content: space-around;
  pointer-events:none;
}

.d-flex:hover a:hover {
  color: black;
}

.d-flex:hover a {
  color: white;
}

.d-flex a {
  color: blue;
  pointer-events:auto;
}
<div class="d-flex">
  <div class="item"><a href="#">item 1</a></div>
  <div class="item"><a href="#">item 2</a></div>
  <div class="item"><a href="#">item 3</a></div>
  <div class="item"><a href="#">item 4</a></div>
</div>

Upvotes: 1

Related Questions