0

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:

  1. In the 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>
  1. 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.

3
  • You can get close with attr() but unfortunately support for anything other than content is sparse at the moment. With current browsers I believe you'll need some javascript. Commented Oct 15, 2019 at 0:56
  • 1
    its confusion as how you would do this during runtime? can you recompile scss after HTML is rendered? Commented Oct 15, 2019 at 0:58
  • 1
    CSS only? Not possible - there's no string concatenation except in the content property. 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). Commented Oct 15, 2019 at 2:18

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah what a great idea!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.