41

我正在研究一个 sass 样式表,我希望在其中使用该calc元素来动态调整某些内容的大小。由于calc元素尚未标准化,我需要定位calc(),-moz-calc()-webkit-calc().

有没有办法让我创建一个可以将表达式传递给的 mixin 或函数,以便它生成所需的标签,然后可以将其设置为 a widthor height

4

4 回答 4

87

这将是一个带有参数的基本 mixin,幸运的是,表达式在支持的范围内不是特定于浏览器的:

@mixin calc($property, $expression) {
  #{$property}: -webkit-calc(#{$expression});
  #{$property}: calc(#{$expression});
}

.test {
  @include calc(width, "25% - 1em");
}

将呈现为

.test {
  width: -webkit-calc(25% - 1em);
  width: calc(25% - 1em);
}

您可能希望在不支持 calc 时包含“默认”值。

于 2012-05-31T01:37:27.503 回答
10

Compass 提供了一个共享实用程序来为这种情况添加供应商前缀。

@import "compass/css3/shared";

$experimental-support-for-opera: true; // Optional, since it's off by default

.test {
  @include experimental-value(width, calc(25% - 1em));
}
于 2013-02-28T18:05:57.410 回答
4

使用 unquote 功能可以很容易地使用 calc:

$variable: 100%
height: $variable //for browsers that don't support the calc function  
height:unquote("-moz-calc(")$variable unquote("+ 44px)")
height:unquote("-o-calc(")$variable unquote("+ 44px)")
height:unquote("-webkit-calc(")$variable unquote("+ 44px)")   
height:unquote("calc(")$variable unquote("+ 44px)")

将呈现为:

height: 100%;
height: -moz-calc( 100% + 44px);
height: -o-calc( 100% + 44px);
height: -webkit-calc( 100% + 44px);
height: calc( 100% + 44px);

您也可以尝试按照上面的建议创建 mixin,但我的做法略有不同:

$var1: 1
$var2: $var1 * 100%
@mixin calc($property, $variable, $operation, $value, $fallback)
 #{$property}: $fallback //for browsers that don't support calc function
 #{$property}: -mox-calc(#{$variable} #{$operation} #{$value})
 #{$property}: -o-calc(#{$variable} #{$operation} #{$value})
 #{$property}: -webkit-calc(#{$variable} #{$operation} #{$value})
 #{$property}: calc(#{$variable} #{$operation} #{$value})

.item     
 @include calc(height, $var1 / $var2, "+", 44px, $var1 / $var2 - 2%)

将呈现为:

.item {
height: 98%;
height: -mox-calc(100% + 44px);
height: -o-calc(100% + 44px);
height: -webkit-calc(100% + 44px);
height: calc(100% + 44px);
}
于 2013-05-30T19:35:33.900 回答
0

另一种写法:

@mixin calc($prop, $val) {
  @each $pre in -webkit-, -moz-, -o- {
    #{$prop}: $pre + calc(#{$val});
  } 
  #{$prop}: calc(#{$val});
}

.myClass {
  @include calc(width, "25% - 1em");
}

我认为这是更优雅的方式。

于 2016-12-22T15:39:33.717 回答