TayIsAsleep
TayIsAsleep

Reputation: 89

How to handle hover in SCSS/SASS

Say I have this custom button:

<div class="button-container">
    <p class="button-text">Click me</p>
</div>

I want the div to have a background color, and the text to have a color in SCSS. But I also need a different background color and text color when I'm hovering the whole div (not just the p tag and div separate, only when hovering the div)

I could write something like this:

div.button-container{
    background-color: white;

    p{
        color: black;
    }

    &:hover{
        background-color: red;

        p{
            color: blue;
        }
    }
}

But this does not look like a good idea, since this will become very complex and hard to manage if there are more elements involved. What is the best solution here?

I don't know exactly what the code I want would look like since I'm pretty new to SCSS, but I am thinking it would look something like this: (ignore syntax here, just an idea of how much shorter I would like it to be)

div.button-container{
    background-color: white, red;

    p{
        color: black, blue;
    }
}

Upvotes: 3

Views: 6921

Answers (1)

Mari Goto
Mari Goto

Reputation: 99

Based on the html you have provided the following scss will be just fine:

.button-container {
  background-color: black;
  color: white;
  
  &:hover {
  background-color: gray;
  color: black;
  }
}

If there are several items involved, you can create some mixins that can be reused. For example. if there are several button-container elements that share the same style in the app, I will make something like this:

@mixin btnContainerBlack {
  background-color: black;
  color: white;
  &:hover {
    background-color: gray;
    color: black;
  }
}

In this case, you will simply add the mixin name to the element style:

.button-container {
  @include btnContainerBlack;
}

There are many ways to make scss more clean and reusable. This is just one of the ideas.

Upvotes: 4

Related Questions