skip to Main Content

I have a following situation:

I have 4 cards in a CSS grid. The first one is supposed to be "featured" (different background, etc.) and on hover on the remaining cards, I would like the feature styling change to a hovered card and "unfeature" the first one.

HTML:

<div class="benefits__grid">
     <div class="benefits__card">
         <h3>Heading</h3>
         <p>Text</p>
     </div>
     <div class="benefits__card">
         <h3>Heading</h3>
         <p>Text</p>
     </div>
     <div class="benefits__card">
         <h3>Heading</h3>
         <p>Text</p>
     </div>
     <div class="benefits__card">
         <h3>Heading</h3>
         <p>Text</p>
     </div>
</div>

I managed to target the featured card by changing the order of elements (so the featured card is last in the DOM but visibly first) and using last-child, as follows:

benefits__card:not(:last-child):hover ~ benefits__card(:last-child) {
    background-color: black;
}

This works properly. I can’t however target the children of the featured card. I would assume something like this should work, but it doesn’t:

benefits__card:not(:last-child):hover ~ benefits__card(:last-child) h3 {
    color: var(--black);
}

Any ideas?

Tried the CSS that is posted in the thread, to no avail.

2

Answers


  1. Chosen as BEST ANSWER

    Pete's code works perfectly, just as I wanted.


  2. You could use a parent hover to cancel the the featured colour:

    .benefits__grid:hover .featured {
      background: transparent;
      color: black;
    }
    
    .featured,
    .benefits__grid .benefits__card:hover {
      background: black;
      color: white;
    }
    <div class="benefits__grid">
      <div class="benefits__card featured">
        <h3>Heading</h3>
        <p>Text</p>
      </div>
      <div class="benefits__card">
        <h3>Heading</h3>
        <p>Text</p>
      </div>
      <div class="benefits__card">
        <h3>Heading</h3>
        <p>Text</p>
      </div>
      <div class="benefits__card">
        <h3>Heading</h3>
        <p>Text</p>
      </div>
    </div>

    If you can’t start with the featured class then you could use these selectors

    .benefits__grid:hover .benefits__card:first-child {
      background: transparent;
      color: black;
    }
    
    .benefits__card:first-child,
    .benefits__grid .benefits__card:first-child:hover,
    .benefits__grid .benefits__card:hover {
      background: black;
      color: white;
    }
    <div class="benefits__grid">
      <div class="benefits__card">
        <h3>Heading</h3>
        <p>Text</p>
      </div>
      <div class="benefits__card">
        <h3>Heading</h3>
        <p>Text</p>
      </div>
      <div class="benefits__card">
        <h3>Heading</h3>
        <p>Text</p>
      </div>
      <div class="benefits__card">
        <h3>Heading</h3>
        <p>Text</p>
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search