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?
Asked
Active
Viewed 4,825 times
3
-
1You 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. – Red Sep 04 '17 at 11:32
-
2Inline css is the best solution. (for me) – Roy Bogado Sep 04 '17 at 11:33
-
Thanks, just wanted to check if there is another way. Hope the attribute passing to CSS will work someday. – The50 Sep 04 '17 at 11:41
1 Answers
4
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

Melcma
- 608
- 3
- 14