Search code examples
htmlcsssasshover

Extend &:hover of any class to any other class's hover in SASS or SCSS


Is there a way to extend &:hover of any class to any other class's hover?

My code is something like this and it stopped the hover of both classes:

HTML

<a href="#" class="button1">Button 1</a>
<a href="#" class="button2">Button 2</a>

SCSS

.button1 {
  background: black;
  padding: 5px 10px;
  text-decoration: none;
  color: white;
  &:hover {
    background: red;
  }
}

.button2 {
  background: blue;
  padding: 5px 10px;
  text-decoration: none;
  color: white;
  &:hover {
    @extend .button1:hover
  }
}

Solution

  • You can use a placeholder.

    %hover {
      background: red;
    }
    
    .button1 {
      background: black;
      padding: 5px 10px;
      text-decoration: none;
      color: white;
      &:hover {
        @extend %hover;
      }
    }
    
    .button2 {
      background: blue;
      padding: 5px 10px;
      text-decoration: none;
      color: white;
      &:hover {
        @extend %hover;
      }
    }
    

    Or, perhaps a better solution, use a more generic class for your buttons:

    .btn {
      padding: 5px 10px;
      text-decoration: none;
      color: white;
    
      &:hover {
        background: red;
      }
    }
    
    .btn--1 {
      background: black;
    }
    
    .btn--2 {
      background: blue;
    }