是否在条件内设置了SASS变量?

CSS

蛋蛋

2020-03-24

我可以在SASS的if / else条件内设置变量吗?假设您要为页面设置2种配色方案。考虑在主体上设置一个类来处理颜色差异,您可以执行以下操作(用英语编写,而不尝试任何正确的语法):

If parent class is red then $main-color = #f00 else $main-color = #000

我可以这样做吗?

第3349篇《是否在条件内设置了SASS变量?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
DavaidTony宝儿 2020.03.24

是的,这是可能的:

$parent: true
$foo: red

@if $parent == true 
  $foo: blue

p
  color: $foo

codepen

但是,值得注意的是,您将无法使用条件检查SASS中父元素(或任何其他元素)属性(请参阅SASS领导的这篇文章),因此parent class 在伪代码中必须被存入骚扰中$variable

小卤蛋 2020.03.24

Sass Variable Scope

Sass supports two types of variables: local variables and global variables.

By default, all variables defined outside of any selector are considered global variables. That means they can be accessed from anywhere in our stylesheets. For instance, here’s a global variable:

$bg-color: green;

On the other hand, local variables are those which are declared inside a selector. Later, we’ll examine how we can customize that behavior. But for now, let’s see our first example.

Here we define a mixin and then the btn-bg-color variable within it. This is a local variable, and is therefore visible only to the code inside that mixin:

@mixin button-style {
    $btn-bg-color: lightblue;
    color: $btn-bg-color;
}

Conclusion

you can use this code to make if directive change in your variable

    $left: left;
    $right: right;

@if $dir == rtl { 
     $left: right;
    $right: left;
}
.pull-left{
   float:#{$left};
}

you can read this article Sass Variable Scope

西里Near 2020.03.24

您可以使用功能。像这样:如何动态更改文本颜色...

@function set-color($class) {
  @if ($class == red) {
    @return #f00;
  } @else {
    @return #000;
  }
}
$main-color = set-color($parent-class);

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android