Frontendplace Blog

Sharing Frontend developing ideas

Archive for April, 2013

Batch generate rules with color codes from a list of colors with SASS

Posted by info on 18th April 2013

Sometimes you need a list of selectors based under different environments and every environment has its own body class. If you need to make a lot of selectors with different colors for every environment it is best to set the list of colors and a list of environments in variables and let sass generate the color rules for every environment.

example:
// first we set the variables:
$darkcolor-df :#E17000; // rgb(225, 112, 0) portaal Defensie bar oranje
$lightcolor-df :#F6D4B2; //Defensie border licht oranje

$darkcolor-km: #0E61AA; //KM bar/border Blauw
$lightcolor-km: #E1EBF4; //.. KM lichtblauw

$darkcolor-kl: #00423C; // KLandmacht bar groen
$lightcolor-kl: #DFE7E7; // KLandmacht border lichtblauw

calling mixin
@include envcolor(background-color, ‘dark’, ‘#navigation .selected a,#navigation .selected a:visited’);

Mixin:

/* -----------------------------------
    mixin for setting the light or dark color per environment
    input param selector 	type:list of strings 	selector string(s) after the environment class
				prop 		type:style property
				clr 		type:string 	dark | light | #000000 colorcode
   ----------------------------------*/
@mixin envcolor($prop, $clr, $selector) {
	$env:  kl, klu, kmar, cmc, dmo;
	$darkcolors: $darkcolor-kl,$darkcolor-klu,$darkcolor-kmar,$darkcolor-cmc,$darkcolor-dmo;
	$lightcolors: $lightcolor-kl,$lightcolor-klu,$lightcolor-kmar,$lightcolor-cmc,$lightcolor-dmo;
	/* #{$clr} */
	@for $i from 1 through length($env) {
        $portal: nth($env, $i);
        $color: #{$clr}  !default;
		
        @if ('#{$clr}'=='dark') {
        	/* #{$portal} dark */
        	$color: nth($darkcolors, $i);
        }
        @else if ('#{$clr}'=='light'){
        	/* #{$portal} light */
            $color: nth($lightcolors, $i);
        } @else {
        	 $color: #{$clr};
        }
		.#{$portal} {
			#{$selector} {
			  	#{$prop} :#{$color};
			}
		}
    }
}

Generates:


/* dark */
/* df dark */
.df #navigation .selected a, .df #navigation .selected a:visited {
background-color: #e17000;
}

/* km dark */
.km #navigation .selected a, .km #navigation .selected a:visited {
background-color: #0e61aa;
}

/* kl dark */
.kl #navigation .selected a, .kl #navigation .selected a:visited {
background-color: #00423c;
}

/* klu dark */
.klu #navigation .selected a, .klu #navigation .selected a:visited {
background-color: #005187;
}...

Posted in Scripting | Comments Off on Batch generate rules with color codes from a list of colors with SASS