3

I have a HTML template with image blocks. Those images are loaded via CSS using background-image. Now the problem is that I can't pass these variables from my PHP code into CSS. The only solutions I manage to think of is to use inline HTML style attribute with background-image link, or just leave the image link as a data attribute in HTML and put the background-image css using JavaScript. Any other ideas?

Using HTML data-attribute to set CSS background-image url

3
  • 1
    You allready named all the possibilities. Inline CSS, data-* or JavaScript. Just choose yourself. Because the awnser(s) will mostly be opinion based. And thats not a awnser that belongs on SO. Commented Sep 4, 2017 at 11:32
  • 2
    Inline css is the best solution. (for me) Commented Sep 4, 2017 at 11:33
  • Thanks, just wanted to check if there is another way. Hope the attribute passing to CSS will work someday. Commented Sep 4, 2017 at 11:41

1 Answer 1

3

If you don't mind inline styles I can recommend using inline background-image anyway. Personally I've never run into problem when I need to update this value and this way seems to be clear and easy if you forEach some elements.

Also the big advantage by using this method is you control content with html/php and styling with actual css, so it might be even better to do it this way instead of passing it to css.

<img class="..." style=background-image: url("<?= $img ?>");>

If you are lazy-loading with javascript, this is as simple as reverting style into some data-attribute like data-bg

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.