CSS Sass 负变量值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13296419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 20:43:28  来源:igfitidea点击:

Sass negative variable value?

csssasscompass-sass

提问by Steve

I have a couple of scss selectors where I use the same amount positive and negative, as in:

我有几个 scss 选择器,我使用相同数量的正负,如下所示:

padding: 0 15px 15px;
margin: 0 -15px 20px -15px;

I'd prefer to use a variable for all the 15px amounts, but this does not work:

我更愿意为所有 15px 数量使用一个变量,但这不起作用:

$pad: 15px;
padding: 0 $pad $pad;
margin: 0 -$pad 20px -$pad;

The margin amounts convert to positive numbers. Am I missing something?

保证金金额转换为正数。我错过了什么吗?

回答by Zoltan Toth

Try it like this

像这样试试

margin: 0 (-$pad) 20px (-$pad);

回答by Vangel Tzo

A more sane solution according to sass guidelines would be to interpolatevariables like the following example:

根据 sass 指南,更明智的解决方案是interpolate使用如下示例的变量:

margin: 0 -#{$pad} 20px -#{$pad};

An example: https://www.sassmeister.com/gist/c9c0208ada0eb1fdd63ae47830917293

一个例子:https: //www.sassmeister.com/gist/c9c0208ada0eb1fdd63ae47830917293

回答by EvilDr

I'm adding my two-penneth after considering the two previous answers, but then reading this (emphasis mine):

在考虑了之前的两个答案后,我添加了我的二分之一,但随后阅读了这篇文章(重点是我的):

You should especially avoid using interpolation like #{$number}px. This doesn't actually create a number! It creates an unquoted string that looks like a number, but won't work with any number operations or functions. Try to make your math unit-clean so that $numberalready has the unit px, or write $number * 1px.

Source

你应该特别避免使用像#{$number}px. 这实际上并没有创建一个数字!它创建一个看起来像数字的不带引号的字符串,但不适用于任何数字操作或函数。尝试使您的数学单元干净,以便$number已经有 unit px,或者写$number * 1px.

来源

Therefore I believe the correct way would be as follows, which preserves the mathematical abilities of SASS/SCSS:

因此,我认为正确的方法如下,它保留了 SASS/SCSS 的数学能力:

$pad: 15px;
padding: 0 $pad $pad;
margin: 0 $pad*-1 20px $pad*-1;