Pass string into variable in sass mixin

烈酒焚心 提交于 2021-02-17 05:17:04

问题


I have a very simple mixin which looks like this:

@mixin global( $variable-name ) {
    font-size:   #{$variable-name}-font-size;
}

I have previously defined variable $input-font-size and pass it into the mixin in the following format

@include global( input );

Problem is that the sass is not converting it and browser returns :

font-size:input-font-size

How should I write my mixin to actually return the value from $input-font-size please?

Thank you for your advice in advance!


回答1:


You can't create a dynamic variables in sass.

'#{}' means it will convert whatever attribute to its plain css form, it won't be treated as a variable it will be treated as a text.

What you can do is create a map for the list of properties and call them inside the mixin.

$input-font-size: 16px;
$textarea-font-size: 14px;


$var-map: (
  input: $input-font-size, 
  textarea:  $textarea-font-size,
);

@mixin global( $variable-name ) {
    font-size:  map-get($var-map, $variable-name);
}

body {
  @include global( input );
}

or if you dont want to create the map then you can simply pass the variable name in the mixin

@mixin sec( $variable-name ) {
  font-size: $variable-name;
}
.text-area {
  @include sec( $textarea-font-size );
}

Sample pen https://codepen.io/srajagop/pen/aWedNM



来源:https://stackoverflow.com/questions/44275996/pass-string-into-variable-in-sass-mixin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!