Skip to content

Instantly share code, notes, and snippets.

@glueckpress
Created July 24, 2014 14:30
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save glueckpress/9b152bd5a1c949d451ec to your computer and use it in GitHub Desktop.
Save glueckpress/9b152bd5a1c949d451ec to your computer and use it in GitHub Desktop.
Dynamically create classes with SASS (from http://www.paulund.co.uk/dynamically-create-css-classes-sass)
$colours:
"red" #FF0000,
"blue" #001EFF,
"green" #00FF00,
"yellow" #F6FF00;
@each $i in $colours{
.#{nth($i, 1)}-background {
background: nth($i, 2);
}
.#{nth($i, 1)}-color {
color:nth($i, 2);
}
}
.red-background {
background: #FF0000;
}
.red-color {
color: #FF0000;
}
.blue-background {
background: #001EFF;
}
.blue-color {
color: #001EFF;
}
.green-background {
background: #00FF00;
}
.green-color {
color: #00FF00;
}
.yellow-background {
background: #F6FF00;
}
.yellow-color {
color: #F6FF00;
}
@ohabash
Copy link

ohabash commented Jan 25, 2017

Thanks!

@zrayev
Copy link

zrayev commented Mar 25, 2018

Thanks!

Copy link

ghost commented Apr 26, 2018

Thanks !

@mathewmvv05
Copy link

Thanks....!

@AR-92
Copy link

AR-92 commented Sep 24, 2018

thanks :)

@owensco
Copy link

owensco commented Oct 31, 2018

Does this still work with version 1.14.3 ? I can't seem to get it to work:

$colours:
  "blue" #22a1c4,
  "green" #02d425,
  "grey" #efefef,
  "lgrey" #02d425,
  "dgrey" #333333,
  "red" #d9534f;

@each $i in $colours{
	.text-#{nth($i, 1)} {
		color:nth($i, 2);
  }
  .bg-#{nth($i, 1)} {
		background: nth($i, 2);
	}
  .border-#{nth($i, 1)} {
		color:nth($i, 2);
	}
}

@jprivet-dev
Copy link

Merci !

@dani-edo
Copy link

Terimakasih :)

@Aabill
Copy link

Aabill commented Feb 11, 2021

Arigato Sensei :-)

@mmradmtr
Copy link

mmradmtr commented Jul 3, 2021

You no longer need to 'nth' when you use the @each

$colours:
"red" #FF0000,
"blue" #001EFF,
"green" #00FF00,
"yellow" #F6FF00;

@each $key, $value in $colours{
.#{$key}-background {
background: $value;
}
.#{$key}-color {
color: $value;
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment