Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a calc mixin to pass as an expression to generate tags?

Tags:

css

sass

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?

like image 243
secretformula Avatar asked May 31 '12 00:05

secretformula


People also ask

How do you write mixin?

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!

How do you define 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.

How does the CALC () function work on values in CSS?

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.


2 Answers

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.

like image 160
Oleg Avatar answered Oct 07 '22 13:10

Oleg


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)); } 
like image 35
steveluscher Avatar answered Oct 07 '22 14:10

steveluscher