Jamie Hutber
Jamie Hutber

Reputation: 28126

Sass variables with same names but different outcomes based on class?

I've tried to wrap my brain round this, I assume that I need an if statement somewhere along the way.

But I'd like to be able to do this with sass. But this will just take the green colour and ignore the default colour regardless of the class.

SASS

//  Default Colours --------------------------------------------------------------
     $textColor: #FFF; 

.green {
   //  Base Colours --------------------------------------------------------------
     $textColor: green; 
}

body {
    text: $textColor
}

HTML

<p>jamie</P> //Output is #FFF

<p class="green">jamie</P> //Output is green

Upvotes: 1

Views: 443

Answers (2)

magicspon
magicspon

Reputation: 926

Here is a little mixin you could use.

$base-color: green;

@mixin change-var($var: $base_color, $selector: x, $property: color) {

    @if $selector == x {
        $var: blue;
    } @else if $selector == y {
        $var: green
    } @else {
        $var: $var;
    }

    #{$property}: $var; 
}

usage:

.x {
    @include change-var($base-color, x, color)
}
.y {
    @include change-var($base-color, y, background-color)
}

output:

.x {
  color: blue;
}

.y {
  background-color: green;
}

Upvotes: 1

mcmac
mcmac

Reputation: 1052

Try this

$textColor: #fff; 
body {
  color: $textColor;
}
.green {
  $textColor: green; 
  color: $textColor;
}

Upvotes: 0

Related Questions