Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

sass

hover

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
  }
}
like image 655
Omer Avatar asked Dec 18 '15 07:12

Omer


2 Answers

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;
}
like image 94
Denis Frezzato Avatar answered Nov 15 '22 09:11

Denis Frezzato


You can use mixin

@mixin hoverStyle {
   &:hover{
     background: red;
   }
}

.button1 {
   background: blue;
   padding: 5px 10px;
   text-decoration: none;
   color: white;
   @include hoverStyle;
}

.button2 {
   background: blue;
   padding: 5px 10px;
   text-decoration: none;
   color: white;
   @include hoverStyle;
}
like image 39
Yasin UYSAL Avatar answered Nov 15 '22 07:11

Yasin UYSAL