Evanion
Evanion

Reputation: 188

Sass/Compass Getting variable name from variable

I'm trying to make a mixin that will let me create adapted blocks of code depending on what variable name you up in.

$foo: #00A9EC;
@mixin menu-color($color) {
.color-#{$color} a.level2,
.color-#{$color} a.level2:visited {
    color: $color;
    &:hover {
        color: adjust-lightness($color, 10); }
    &:active {
        color: adjust-lightness($color, -10); } } }

@include menu-color($foo);

outputs:

.color-foo a.level2,
.color-foo a.level2:visited {
    color: #00A9EC; }

.color-foo a.level2:hover,
.color-foo a.level2:visited:hover {
        color: #20C0FF; }

.color-foo a.level2:active,
.color-foo a.level2:visited:active {
        color: #0084B9; }

Upvotes: 5

Views: 9756

Answers (2)

Vočko
Vočko

Reputation: 2996

In sass you can do this using map, you just pass the variable name instead of the variable itself:

$colors: ( 
    -black: #000,
    -blue: #088DC6
);

@mixin generateBgColor($colorName) {
    .bg-color#{$colorName} {
        background-color: map-get($colors, $colorName);
    }
}

@include generateBgColor("-blue");

This will generate class:

.bg-color-blue {
    background-color: #088DC6;
}

You achieve this also in less with standard variables, just by using curly brackets and double at character:

@blue: #088DC6;

.generate-bg-color(@color) {
    .bg-color-@{color} {
        background-color: @@color;
    }
}

.generate-bg-color(~"blue");

Upvotes: 4

bookcasey
bookcasey

Reputation: 40503

You should not name CSS classes after specific colors. You would regret that. Just think, if you want to make the color red later on, you would need to go back over all your html and change the classes.

The reason we have CSS is so that you don't have to embed style information in the markup.

Use a semantic class the describes the data, not how it is displayed:

$foo: #00A9EC;

@mixin menu-color($name, $color) {
.custom-#{$name} a.level2,
.custom-#{$name} a.level2:visited {
    color: $color;
    &:hover {
        color: adjust-lightness($color, 10); }
    &:active {
        color: adjust-lightness($color, -10); } } }

@include menu-color(profile, $foo);

And then in your HTML <div class="custom-profile">.

That way, two years from now when you want to make it black, and underlined (or whatever), you don't have to dig through your html and add a new '.underlined-and-black-color` class to all of those elements. You just change your SCSS in one place.

Upvotes: 1

Related Questions