Kamil Dzieniszewski
Kamil Dzieniszewski

Reputation: 558

How to use ACF image field in css with media queries using Timber template engine?

I'm writing wordpress theme using Tiber and have really interesting case regarding different images on mobile and desktop.

Case: I would like to upload 2 images (mobile and desktop version) using Advanced Custom Field PRO in Wordpress and use them in custom Timber template engine theme.

Code:

.twig

 <div class="application--main-image"></div>

.scss

.application-main-image {
  background-position: center bottom;
  background-repeat: no-repeat;
  background-image: url('../img/mobile.png');
  @media (min-width: 600px) {
    background-image: url('../img/desktop.png');
  }
}

I found that I should use inline-style to put {{ post.image }} inside background-image but what about media queries?

Should I make some custom attributes or style inside .twig file with <style></style> but I want to use scss so it's not the case.

How would you solve that problem?

Upvotes: 0

Views: 1332

Answers (1)

robertguss
robertguss

Reputation: 175

This is certainly a unique use case, here are my thoughts on how I would approach this:

<style>
  .application--main-image {
    background: url('https://source.unsplash.com/500x500/?ocean');
    /* The actual URL would be replaced by your ACF Filed {{ post.mobile_image }} */
  }

  @media (min-width: 600px) {
    .application--main-image {
      background: url('https://source.unsplash.com/500x500/?mountain');
      /* The actual URL would be replaced by your ACF Filed {{ post.desktop_image }} */
    }
  }

</style>

<div class="application--main-image"></div>

I think you are correct in that you will need to add the tags and the css necessary to your .twig template. I know you want to use .scss, however you only really need to change the background image property. I have create a JS fiddle to show you what I mean.

https://jsfiddle.net/robertguss/2kacx91k/7/

I hope that helps. If you have already come up with a solution that is different than mine, please share it here so not only I can learn but others in the future as well.

Cheers.

Upvotes: 1

Related Questions