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:
- In the
HTML divI would like to set acss varordata-attributenamedbackgroundthat 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>
- Use that image name to do something like: Tried the following code and I know this does not work, I'm just seeing if something like this is possible.
// 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.
attr()but unfortunately support for anything other than content is sparse at the moment. With current browsers I believe you'll need some javascript.contentproperty. You could do this pretty cleanly in SCSS, but it would still transpile to separate lines of CSS for each element/image. Also, your last SCSS example would not be possible because you're trying to apply a CSS variable (determined at browser runtime) into a SCSS mixin (which are resolved in development before CSS compilation).