26

I like to use rem units with pixel fallbacks for my CSS sizing and am trying to make mixins to help with that. For font-size, this is easy:

@mixin font-size($size) {
  font-size: $size + px;
  font-size: ($size / 10) + rem;
}

But for padding, margin, etc. the mixin needs to accept variable arguments, which is possible per the Sass documentation http://sass-lang.com/documentation/file.SASS_REFERENCE.html#variable_arguments

However, with the following mixin, instead of dividing by 10, the mixin is just adding a slash between the numbers. That is, this:

@mixin padding($padding...) {
    padding: $padding + px;
    padding: ($padding / 10) + rem;
}
.class {
    @include padding(24);
}

Outputs this:

.class {
    padding: 24px;
    padding: 24/10rem;
}

Instead of this, like I would expect:

.class {
    padding: 24px;
    padding: 2.4rem;
}

Is there a way to make sure Sass recognizes the variables as numbers and thus uses the division operator on them correctly?

Also, after testing this more, I realized the concatenation only takes place on the last variable.

4

3 回答 3

29

尝试这个:

padding: #{$padding / 10}rem;

SASS/SCSS 中的连接使用 ruby​​ 语法,并且您混合了一个数学方程式,然后是一个连接,这是一种可变类型的混合,所以它不起作用对我来说并不奇怪。

#{here} 中包含的表达式和变量被评估为与行的其余部分分开,因此不会对行的其余部分进行类型转换。如果您的输出在您不期望的情况下被引用(就像 unquote() 函数一样),也会派上用场

于 2013-10-17T10:44:05.313 回答
21

看来我在这里真正需要使用的是一个列表而不是一个变量参数,以便分别操作每个值。

我首先尝试使用 @each 指令执行此操作,但无法弄清楚如何在声明中使用它。这会引发错误:

@mixin padding($padding) {
   padding: @each $value in $padding { $value + px };
   padding: @each $value in $padding { ($value / 10) + rem };
}

所以我最终写了一些更冗长的东西,分别处理四种可能的情况(即你传递 1、2、3 或 4 个参数)。看起来像这样并且可以按我的意愿工作:

@mixin padding($padding) {
    @if length($padding) == 1 {
        padding: $padding+px;
        padding: $padding/10+rem;
    }
    @if length($padding) == 2 {
        padding: nth($padding, 1)+px nth($padding, 2)+px;
        padding: nth($padding, 1)*0.1+rem nth($padding, 2)*0.1+rem;
    }
    @if length($padding) == 3 {
        padding: nth($padding, 1)+px nth($padding, 2)+px nth($padding, 3)+px;
        padding: nth($padding, 1)*0.1+rem nth($padding, 2)*0.1+rem nth($padding, 3)*0.1+rem;
    }
    @if length($padding) == 4 {
        padding: nth($padding, 1)+px nth($padding, 2)+px nth($padding, 3)+px nth($padding, 4)+px;
        padding: nth($padding, 1)*0.1+rem nth($padding, 2)*0.1+rem nth($padding, 3)*0.1+rem nth($padding, 4)*0.1+rem;
    }
}

我收集了 rem mixins,包括这个作为 Gist 在这里https://gist.github.com/doughamlin/7103259

于 2013-10-22T17:38:20.300 回答
0

可能有帮助的一件事是calcinterpolation(aka #{}) 一起使用。例如。

$height: 10px;
$padding: 2px;

height: calc(#{$height} + #{$padding * 2}); // calc(10px + 4px)

这和...一样

height: calc($height + #{$padding * 2});
// resolves to...
height: calc($height + 4px); // ERROR

height: #{$height + $padding * 2};
// resolves to...
height: 10px + 4px; // ERROR
于 2021-03-15T18:40:13.043 回答