I am working on a sass stylesheet in which I wish to use the calc
element to dynamically size some content. As the calc
element has not been standardized, I need to target calc()
, -moz-calc()
, and -webkit-calc()
.
Is there a way for me to create a mixin or function that I can pass an expression to so that it will generate the required tags that can then be set as a width
or height
?
A mixin is defined with the @mixin directive. Tip: A tip on hyphens and underscore in Sass: Hyphens and underscores are considered to be the same. This means that @mixin important-text { } and @mixin important_text { } are considered as the same mixin!
As defined in Wikipedia, a mixin is a class containing methods that can be used by other classes without a need to inherit from it. In other words, a mixin provides methods that implement a certain behavior, but we do not use it alone, we use it to add the behavior to other classes.
The calc() function takes a single expression as its parameter, with the expression's result used as the value. The expression can be any simple expression combining the following operators, using standard operator precedence rules: + Addition.
It would be a basic mixin with an argument, thankfully the expressions are not browser-specific within the supported scope:
@mixin calc($property, $expression) { #{$property}: -webkit-calc(#{$expression}); #{$property}: calc(#{$expression}); } .test { @include calc(width, "25% - 1em"); }
Will render as
.test { width: -webkit-calc(25% - 1em); width: calc(25% - 1em); }
You may want to include a "default" value for when calc is not supported.
Compass offers a shared utility to add vendor prefixes for just such an occasion.
@import "compass/css3/shared"; $experimental-support-for-opera: true; // Optional, since it's off by default .test { @include experimental-value(width, calc(25% - 1em)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With