Home > OS >  CSS plus with multiple selectors
CSS plus with multiple selectors

Time:05-27

When using plus ( ) in CSS for sibling selectors, is there a way to select multiple elements?

For example, this will color the background of the second inner div:

.item1:hover   .item2 div {
  background: red;
}
<div>
<div >
  <div>Hover me please</div>
</div>
<div >
  <div>Color me please</div>
</div>

<div >
  <div>Color me two please</div>
</div>

</div>

But I'd like to also select .item3 div as well. I tried it like this, but that doesn't work:

.item1:hover   .item2 div   .item3 div {
  background: red;
}
<div>
<div >
  <div>Hover me please</div>
</div>
<div >
  <div>Color me two please</div>
</div>

<div >
  <div>Color me three please</div>
</div>

</div>

Will I have to use the JS for this or is there a CSS way that I'm missing?

CodePudding user response:

The adjacent sibling selector ( ) will only select the element directly following-- you want the general sibling combinator (~). See below for an example:

.item1:hover ~ .item2 div,
.item1:hover ~ .item3 div {
  background: red;
}
<div>
<div >
  <div>Hover me please</div>
</div>
<div >
  <div>Color me two please</div>
</div>

<div >
  <div>Color me three please</div>
</div>

</div>

(For what it's worth, connexo's answer leverages this same approach, but also makes selection more succinct by leveraging the :is() pseudo-class.)

Update

Regarding this comment:

They are both great solutions, although I just noticed one more thing, if I want to hover 2nd element to color 1st and 3d, in that scenario both of your solutions won't catch the 1st element. In other words, the elements that are behind the hovered element, won't react to this.

This is a slightly different scenario than is stated in the original question. Getting a previous sibling with CSS is, as far as I am aware, still not possible. However, we can cheat it by coloring all the targeted descendants on hover of the wrapper, and then resetting the currently hovered descendant. See below for an example:

.outer-wrapper:hover > div > div {
  background-color: red;
}

.outer-wrapper > div > div:hover {
  background-color: initial;
}
<div >
  <div >
    <div>Hover me please</div>
  </div>
  <div >
    <div>Color me two please</div>
  </div>

  <div >
    <div>Color me three please</div>
  </div>
</div>

CodePudding user response:

~ :is() @supports

.item1:hover ~ .item2 div,
.item1:hover ~ .item3 div {
  background: red;
}

@supports selector(:is()) {
  .item1:hover~ :is(.item2, .item3) div {
    background: orange;
  }
}
<div >
  <div>Hover me please</div>
</div>
<div >
  <div>Color me two please</div>
</div>
<div >
  <div>Color me three please</div>
</div>

CodePudding user response:

Try the below code

.item1:hover ~ :is(.item2, .item3) div {
  background: red;
}
<div>
<div >
  <div>Hover me please</div>
</div>
<div >
  <div>Color me two please</div>
</div>

<div >
  <div>Color me three please</div>
</div>

</div>

  • Related