开发者

Defining variable overrides in SASS / SCSS

开发者 https://www.devze.com 2023-03-26 17:38 出处:网络
I\'ve used sass before and have a question relating to it for functionality I think may or should exist within sass.

I've used sass before and have a question relating to it for functionality I think may or should exist within sass.

Is it at all possible to do something like this, and how:

$base-color: #ffffff;
.pink {
  $base-color: #ec008c;
}
.green {
  $base-color: #a4d20e;
}
a, .pink a, .green a {
  color: $base-color;
}

Which would mean that I could give a class .pink to the <body> element, which would make all <a> elements within that page 开发者_运维知识库"pink". This albeit an oversimplified example seems like something SASS should do.

Which means the above scss would compile so something like so:

a {
  color: #ffffff;
}
.pink a {
  color: #ec008c;
}
.green a {
  color: #ec008c;
}

Which as I said before is over simplified, consider the following:

$base-color: #ffffff;
.pink {
  $base-color: #ec008c;
}
.green {
  $base-color: #a4d20e;
}
.pink, .green {
  #header #nav li a {
    color: $base-color;
  }
}

Should give me something like so:

.pink #header #nav li a {
    color: #ec008c;
}
.green #header #nav li a {
    color: #a4d20e;
}

This seems like something that should be doable in SCSS/SASS and would pay A Lot of dividends on larger projects, in both coding time and maintainability.


I don't know if there is any way of making SASS work using the syntax that you've proposed, but you can achieve a similar effect using mixins. This is how I would do it:

@mixin anchor { color: $base-color; }
@mixin headernav {
  #header #nav { color: $base-color; }
  #header #nav li a { color: $base-color; }
}

$base-color: #ffffff;
a { @include anchor; }
@include headernav;

.pink {
  $base-color: #ec008c;
  a { @include anchor; }
  @include headernav;
}

.green {
  $base-color: #a4d20e;
  a { @include anchor; }
  @include headernav;
}

This produces the following CSS output:

a {
  color: white; }
#header #nav {
  color: white; }
#header #nav li a {
  color: white; }

.pink a {
  color: #ec008c; }
.pink #header #nav {
  color: #ec008c; }
.pink #header #nav li a {
  color: #ec008c; }

.green a {
  color: #a4d20e; }
.green #header #nav {
  color: #a4d20e; }
.green #header #nav li a {
  color: #a4d20e; }

Basically, you could build an entire stylesheet as a mixin, then @include that mixin inside of your .pink and .green classes.

0

精彩评论

暂无评论...
验证码 换一张
取 消