skip to Main Content

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.

Thanks

2

Answers


  1. You don’t pass HTMl to CSS. When Liquid renders your theme into a big string of HTML, you can use the vendor of the product to affect the CSS you show to the customer. Either you set the specific crap you need in your CSS ahead of time, and just switch this way, or you suck the crap out of say product metafields and use it that way. In other words, since you can save a string as a metafield, and CSS is a string, you could do it that way too.

    Login or Signup to reply.
  2. You could do that with CSS variables (a.f.a.i.k. there is no other way).

    https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search