Matt Messinger
Matt Messinger

Reputation: 57

Override SASS variable inside of a selector

I'm trying to override the value of a variable when the body has a specific class on it. I'm hoping to be able to change to different 'themes' based on this class that I add to the body.

A default variable for my primary color

$primary: #6cc907;

Override the primary variable

.branded {
  $primary: #e43e94;
}

Upvotes: 1

Views: 5820

Answers (1)

kunalbhat
kunalbhat

Reputation: 1719

Consider using a mixin instead of a variable for this application. In your selector, you can include the mixin and pass it a variable. You can even set a default value for the mixin variable, in this case your base background-color. Override it by passing the mixin a new value.

Sass

@mixin bg-color($primary: #6cc907) {
  background-color: $primary;
}

div {
  @include bg-color(); // Use default value

  display: inline-block;
  height: 300px;
  width: 200px;

  &.branded {
    @include bg-color(#e43e94); // Override value
  }
}

Codepen example

Upvotes: 4

Related Questions