简体   繁体   English

制作动态 SCSS 方法来更改变量值

[英]Make a dynamic SCSS method to change variable values

I have done a project with a lot of code duplicity, so the problem occurs because I have to write the class in each query.我做了一个代码重复很多的项目,所以出现问题是因为我必须在每个查询中编写class。 I'm trying to improve performance here.我正在努力提高这里的性能。 In order to do that, I want to use dynamic values for styling.为此,我想使用动态值进行样式设置。 For example, the way CSS is being used here, but in ten different places using the same animation.例如,这里使用的是 CSS 的方式,但在十个不同的地方使用了相同的 animation。

$center : 590px;

.container {
  width: $center;
 }

@media only screen and (max-width: 1660px){
//here I want to change $center to 490px;
// =================================================
// but the way that I found is to duplicate it 
$center: 490px;

.container {
  width: $center;
 }
/*note : if I don't call the '.container' everytime that I'm changing the $center variable it does not work,
I have some animations that must use the variables .
*/

}

You can make use of @mixin and @include to avoid duplication.您可以使用@mixin@include来避免重复。

@mixin media-container($center) {
  @media only screen and (max-width: 1660px) {
    .container {
      width: $center;
    }
  }
}

In order to use the @mixin in any classes you want, you can add the following to the class you want to use this in:为了在您想要的任何类中使用@mixin ,您可以将以下内容添加到您想要使用的 class 中:

.container-class {
    @include media-container(540px);
}

Note that the 540px above can be replaced with any configuration you want for $center variable, which would change the width for your container.请注意,上面的540px可以替换为$center变量所需的任何配置,这将改变容器的宽度。

Documentation: https://sass-lang.com/documentation/at-rules/mixin文档: https://sass-lang.com/documentation/at-rules/mixin

SCSS variables are static (compile time) to do what you want you need to use CSSVariables that are dynamic (run time) - something like this SCSS 变量是 static(编译时)来做你想做的事,你需要使用动态的 CSSVariables(运行时)——像这样

.container {
  width: var(--width, 590px); /* default */
}

@media only screen and (max-width: 1660px){
  .container { 
     --width: 490px; 
  }
}

If you need to set multiple values - you can use Sass nesting to make it a little easier to type如果您需要设置多个值 - 您可以使用 Sass 嵌套使其更容易键入

.container {
  width: var(--width, 50px);
  @media (min-width: 100px) { --width: 100px; }
  @media (min-width: 200px) { --width: 200px; }
  @media (min-width: 300px) { --width: 300px; }
  ...
}


// output
.container { 
   width: var(--width, 50px); 
} 
@media (min-width: 100px) { 
  .container { --width: 100px; } 
}
@media (min-width: 200px) { 
  .container { --width: 200px; } 
}
@media (min-width: 300px) { 
  .container { --width: 300px; } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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