Pass Html Variables To Css

- 1 answer

I've done a fair bit of searching, but not come across any recent, useful answers.

My question is whether it's possible to pass variables from HTML (possibly using data attributes) into CSS?

My use case is that I have brand pages that I'd like to use a media query to show vendor-specific backgrounds for each brand using media queries. I know you can't use media queries in inline CSS, but I equally don't want to create ~100 media queries in my style sheet.

On my HTML page, i can access an object for the vendor background URL, so it would be great if I could pass these into a single CSS media query somehow without doing any javascript.




You could do that with CSS variables (a.f.a.i.k. there is no other way).

It would work something like this:

  • Attach a CSS variable to your HTML tag: <html style="--variable:'your_fallback_image.jpg'">
  • Populate that variable with the URL dynamically (doesn't matter how for this example)
  • Create CSS that would set a background (wrapped in the media-query)

Something like below:

@media screen and (width:64rem){
  background-image: url(--variable);

Now it should update accordingly when changing the URL, and set a default in case your dynamic solution does not wor. hope that helps.