我正在製作一個sass樣式表,我希望使用calc
元素動態調整某些內容的大小。由於calc
元素尚未標準化,因此我需要針對calc()
,-moz-calc()
和-webkit-calc()
。如何創建一個calc mixin作爲表達式傳遞以生成標記?
有沒有辦法讓我創建一個mixin或函數,我可以傳遞一個表達式,以便它會生成所需的標記,然後可以設置爲width
或height
?
我正在製作一個sass樣式表,我希望使用calc
元素動態調整某些內容的大小。由於calc
元素尚未標準化,因此我需要針對calc()
,-moz-calc()
和-webkit-calc()
。如何創建一個calc mixin作爲表達式傳遞以生成標記?
有沒有辦法讓我創建一個mixin或函數,我可以傳遞一個表達式,以便它會生成所需的標記,然後可以設置爲width
或height
?
這將是一個基本的mixin with an argument,幸好表達式不特定瀏覽器所支持的範圍之內:
@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的默認值。
羅盤優惠a shared utility爲這種場合添加供應商前綴。
@import "compass/css3/shared";
$experimental-support-for-opera: true; // Optional, since it's off by default
.test {
@include experimental-value(width, calc(25% - 1em));
}
不允許使用變量。怎麼樣:''@include experimental-value(width,calc(100% - ($ sidebarWidth + $ padding)));''? – user1429980
還沒有嘗試過,但是這樣做的工作? '@include experimental-value(width,calc(100% - #{$ sidebarWidth + $ padding}));' – steveluscher
[shared utility](http://compass-style.org/reference/compass/css3/shared /#mixin-experimental-value)已從指南針中棄用。 –
使用鈣可全美基礎很容易地使用所享有的特徵:
$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);
您也可以嘗試創建混入按照以上建議,但我做我的略有不同:
$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);
}
另一種方式來寫它:
@mixin calc($prop, $val) {
@each $pre in -webkit-, -moz-, -o- {
#{$prop}: $pre + calc(#{$val});
}
#{$prop}: calc(#{$val});
}
.myClass {
@include calc(width, "25% - 1em");
}
我覺得這是更優雅的方式。
這是完美的我不知道你可以將一個屬性傳遞給一個mixin,但它現在有意義 – secretformula
不要只是繞過添加前綴willy-nilly。 Opera目前不支持'calc()',但是當它出現時,很可能不用前綴。 – cimmanon
如果你正在使用[波旁](http://www.bourbon.io),有一個[calc mixin](https://github.com/thoughtbot/bourbon/blob/master/app/assets/stylesheets/ css3/_calc.scss)內置。 –