SCSS and the power of mixins

I have been working with SASS for sometime now. Today I came across an interesting issue where i had to style individual elements that had specific styles attached to it.

<div style="font-size:12px;padding-left:20px;margin-right:5px;"&gt;
    An
       <div style="font-size:16px;margin-top:10px;padding-right:10px">
            awesome
       </div>
   product, Tell me about it!
</div>

So I wrote a mixin as below:

@mixin generateClassNamesWithVariables($start,$stop, $classname, $css-element, $spacer){
	@for $i from $start through $stop {
	    .#{$classname}#{$i*$spacer} { #{$css-element}: #{$i * $spacer}px; }
	}
}

This is how i have used the above mixin:

@include generateClassNamesWithVariables(1,5,margin-,margin,10);
@include generateClassNamesWithVariables(1,5,margin-top-,margin-top,10);
@include generateClassNamesWithVariables(1,5,margin-bottom-,margin-bottom,10);
@include generateClassNamesWithVariables(1,5,pad-right-,padding-right,10);
@include generateClassNamesWithVariables(1,5,pad-left-,padding-left,10);
@include generateClassNamesWithVariables(1,5,pad-top-,padding-top,5);
@include generateClassNamesWithVariables(1,5,pad-bottom-,padding-bottom,5);
@include generateClassNamesWithVariables(1,5,pad-,padding,10);
@include generateClassNamesWithVariables(10,30,f,font-size,1);

So what this mixin will do is generate the following css.

Now the html will be something like this, it is much cleaner and works like a charm!

<div class="f12 pad-left-20 margin-right-5">
        An  <div class="f16 margin-top-10 pad-right-10">
            awesome</div>
       product
</div>
4 Comments

Add a Comment

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image