I'm trying to grasp some new css concepts and I have some ideas but I'm curious how others would optimize this css code. It's in regards to implementing custom colors in gutenberg theming.
.has-blue-background-color li a,
.has-blue-background-color p,
.has-blue-background-color h1,
.has-blue-background-color h2,
.has-blue-background-color h3,
.has-blue-background-color h4,
.has-blue-background-color h5,
.has-blue-background-color blockquote,
.has-blue-background-color blockquote p,
.has-blue-background-color blockquote cite,
.has-blue-background-color li,
.has-green-background-color li a,
.has-green-background-color p,
.has-green-background-color h1,
.has-green-background-color h2,
.has-green-background-color h3,
.has-green-background-color h4,
.has-green-background-color h5,
.has-green-background-color blockquote,
.has-green-background-color blockquote p,
.has-green-background-color blockquote cite,
.has-green-background-color li {
color: #fff;
}
Some sort of css-preprocessor or postcss that allows for nesting will help you quite a lot.
//scss
.has {
&-background {
&-blue {
&-color {
p {...}
li {....}
}
}
}
&-background {
&-red {
&-color {
p {...}
li {...}
}
}
}
}
Eventually I'd even shift the verbs and ditch color
. Simply to write less code overall. While has-blue-background
reads better than has-background-blue
, you save writing -background
for each and every color you have.
//scss
.has {
&-background {
&-blue {
p {...}
}
&-green {}
&-orange {}
}
}
The &
is basically a "append" whatever follows after it to the parent class inside that nesting. Without the ampersand you just have your normal rule as you'd expect in css.
Perhaps you can even write a dynamic mixin for this, to not write the scss for all these colors, but rather use a function.