skip to Main Content

I have this simple code:

<div class='card'>
  <div class='upper-body"> .. </div>
  <div class="lower-body"> .. </div>
</div>

I want when you hover over the upper-body, a border to be added on the entire card, but when you hover over the lower-body, nothing to be added. The upper-body is basically the entire card, and the lower-body is the button at the bottom of the Card.

I tried this:

 .card { 
    &:hover:not(.lower-body) { 
    cursor: pointer;
    border-color: #0A8276;
   }
}

..but it’s not working. Border is added even when I hover over the lower-body. Why? Why is it not excluded?

3

Answers


  1. There are several errors.

    1. <div class='upper-body"> starts with ‘ and ends with "
    2. .card { &:hover:not(.lower-body) { means that you write it for the .card element and not for its children – you shouldn’t use the & character.

    Use this code:

    .card>div{
      border:5px solid;
    }
    .card div:not(.lower-body):hover{ 
      cursor: pointer;
      border-color: #0A8276;
    }
    <div class="card">
      <div class="upper-body"> .. </div>
      <div class="lower-body"> .. </div>
    </div>

    For SCSS the code is this:

    .card { 
      div:not(.lower-body)&:hover { 
        cursor: pointer;
        border-color: #0A8276;
      }
    }
    

    Or if it’s supposed to be all on hover, then this code:

    .card>div{
      border:5px solid;
    }
    .card:hover div:not(.lower-body){ 
      cursor: pointer;
      border-color: #0A8276;
    }
    <div class="card">
      <div class="upper-body"> .. </div>
      <div class="lower-body"> .. </div>
    </div>

    For SCSS the code is this:

    .card { 
      &:hover div:not(.lower-body) { 
        cursor: pointer;
        border-color: #0A8276;
      }
    }
    
    Login or Signup to reply.
  2. there is no way to style an element based on its children hover state.
    you can get your desired look by 2 way:

    1.add a class using javascript to card when user hover on upper-body and then set border style based on this class.

    2.use upper-body::after this way:

    .card,.lower-body {
        position: relative;
    }
    .upper-body:hover::before {
        content: "";
        display: block;
        position: absolute;
        border: 1px solid;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        z-index: 0;
    }
    
    Login or Signup to reply.
  3. For future reference, this is possible with :has. But this is not widely supported yet.

    .card:has(.upper-body:hover) {
      border: 1px solid #0A8276;
    }
    <div class="card">
      <div class="upper-body"> Hover Me </div>
      <div class="lower-body"> Lower Body </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search