Jamie
Jamie

Reputation: 2081

Retrieve data from html to use with SCSS/CSS

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.

Upvotes: 0

Views: 794

Answers (1)

mtk
mtk

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

Related Questions