Reputation: 2081
I have several different templates that use different background images. While I know I can inline the background image or create multiple classes
to use different background images — I am trying to be creative while making my life easier. Here is what I am aiming for:
HTML div
I would like to set a css var
or data-attribute
named background
that holds the image name. So for example:<div class="bg-image" style="--background: 'image-name'"></div>
or (which I don't think is possible)
<div class="bg-image" data-attr="image-name"></div>
// tried this
background-image: url("../images/"var(--background)".jpg");
// also tried this, which I think essentially does the same thing
@mixin form-bg-image($slug) {
background-image: url("../images/#{$slug}.jpg");
}
.bg-image {
@include form-bg-image(var(--background));
}
Not sure if this is possible without JS, I just think it would be cool to do! Looking for any solutions using SCSS
and CSS
.
Upvotes: 0
Views: 794
Reputation: 77
Maybe you could have a SCSS dependency file with an array, that would map [data-attr=""]
elements to background-image
property. But that is probably not life made easier solution.
What SCSS -> CSS
compiler do you use? If you wrap it in a grunt task runner, you can scan your html files for specific data attributes and include values into dependency before triggering compilation itself.
Upvotes: 1