Sass mixin to have multiple theme based background images
Let’s say you want to have themed background images on your website aswell as a different one depending on wether it is day or night.
Sure you could achieve this with javascript and just replace the background image. But this time I wanted to to this only via css.
These are the images we want.
If we wanted to do this in CSS we have classes for each season and another one for the themes (light and dark). But what happens if we add another theme? Or whe change the filetype of the photos?
Then we would have to change a lot of code.
This mixin saves us:
$seasons: (spring, autumn);@mixin bgImageWithSeason($theme) {
@each $season in $seasons {
&.#{$season} {
background: url('/assets/img/' + $season + '_' + $theme + '.jpg') no-repeat center;
background-size: contain;}
}
}
In the code we simply reference it like this and include another image for every class we have. The season gets included automatically for every class and we simply have to specify the theme we want.
// Needs images hero_{spring/autumn}_{dark/light}.jpg
.hero {
min-height: 100px;@include bgImageWithSeason('light');&.dark {
@include bgImageWithSeason('dark');
}}
The theme is just an idea. I used it to have different photos with text on it in different languages.