Is it possible to write a class with predefined color-HexCodes? So that in my HTML I can create elements like:
$yellow: #FFFF00;
.color($colorName) {
color: $colorName;
}
<div class="color(yellow)">
</div>
This would be my problems solution. My problem is that I have too much classes with different colors in my .scss file.
Thanks
You can achieve this in SCSS fairly easily. For the quick solution: here's the code in a JSfiddle.
The more elaborate explanation:
Since SASS 3.3 you can use the map data structure. They store a mix of key/value pairs:
$map: (key1: value1, key2: value2, key3: value3);
So, in your case, you could create a map of colors (as long or as short as you like) for later reference:
$colors: (
red: #ff0000,
yellow: #ffd000,
blue: #00baff,
green: #00ff00
);
Now, to generate the CSS classes you need to loop over the map with a nice bit of SASS:
@each $colorname, $color in $colors {
.square--#{$colorname} {
background-color: $color;
}
}
All this @each
loop does is cycle over each key/value pair in $colors, assigning the key (e.g: red) to $colorname and the value (e.g: #ff0000) to $color.
The compiled CSS would be:
.square--red { background-color: #ff0000; }
.square--yellow { background-color: #ffd000; }
.square--blue { background-color: #00baff; }
.square--green { background-color: #00ff00; }
If in the future you want to add a new color it's as simple as adding a key/value pair to the $colors map and compiling!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With