csscss-selectors

Is there a way to use the subsequent-sibling combinator so that it matches only the first instance?


I'm trying to figure out a way--when hovering on an element--to affect that element and the next subsequent-sibling ONLY. In my example below, when I hover over the Header I only want the next Footer to also be highlighted, not all of them. I realize it's working correctly the way it's written in this example, but I'm hoping that there's a CSS-only solution that doesn't require some JS to get it to work the way I want it to.

.header:hover {
  background-color: yellow;
}
.header:hover ~ .footer,
.header.hover ~ .footer {
  background-color: yellow;
}
<div class="header">Header</div>
<div class="footer">Footer</div>
<div class="header">Header</div>
<div class="footer">Footer</div>
<div class="header">Header</div>
<div class="footer">Footer</div>
<div class="header">Header</div>
<div class="footer">Footer</div>


Solution

  • You are currently using the Subsequent-sibling combinator with the ~ operator:

    The subsequent-sibling combinator is made of the "tilde" (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.

    (emphasis mine)

    But what you are looking for is the Next-sibling combinator with the + operator:

    The next-sibling combinator is made of the "plus sign" (U+002B, +) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence immediately precedes the element represented by the second one.

    (emphasis mine)

    See the following code

    .header:hover {
      background-color: yellow;
    }
    .header:hover + .footer {
      background-color: yellow;
    }
    <div class="header">Header</div>
    <div class="footer">Footer</div>
    <div class="header">Header</div>
    <div class="footer">Footer</div>
    <div class="header">Header</div>
    <div class="footer">Footer</div>
    <div class="header">Header</div>
    <div class="footer">Footer</div>