简体   繁体   中英

How to DRY Sass code using variables?

I have a design that uses colors to identify sections of the site. I have put a file with the color variables defined, since they can change and it is difficult to track them down through the CSS files.

$people: #D50000;
$galleries: #D500AA;
$projects: #D5BA00;
//etc...

The name of my classes matches those of the variables. For example, the navigation menu is something like:

<ul>
  <li class="people">People</div>
  <li class="galleries">Galleries</div>
  <li class="projects">Projects</div>
  <!-- etc... ->
</ul>

and I find myself writing SASS like

#nav {
  ul {
    li.people    { border-left: 5px solid $people;    }
    li.galleries { border-left: 5px solid $galleries; }
    li.projects  { border-left: 5px solid $projects;  }
  }
}

which I'd like to DRY up. I have tried to use mixins, but I don't know how to tell SASS to lookup a variable named after the argument I pass (variable indirection). I have something like:

@mixin menu-states($resource) {
  li.#{$resource} a {                     // This works
    border-left: 7px solid $#{$resource}; // But this doesn't...
  }
}

Does anybody have a suggestion on how to DRY this? Thanks.

this code works for me

@mixin test($resource: "red"){
    $updated: unquote($resource);
    li.#{$updated} a{
        border-left: 7px solid $updated;
    }
}

您不能这样做,但是可以将2个变量传递给mixin,一个用于类,另一个用于颜色。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM