Home » Featured, Headline, Mobile Development, Software Development

SCSS and the power of mixins

24 July 2012 4 Comments

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 »

  • fai said:

    good post mate, keep it up…chuur…

  • Penny Imes said:

    Hello there, I found your blog via Google at the same time as looking for a related topic, your website came up, it appears great. I’ve bookmarked it in my google bookmarks.

  • DianneLVoros said:

    What’s up to every single one, it’s in fact
    a nice for me to pay a quick visit this web page, it consists of important Information.

  • Anonymous said:

    An intriguing discussion may be worth comment. I think that
    you need to write a little more about this issue.

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.

*
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