Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML passing image URL variable to CSS [closed]

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

like image 631
The50 Avatar asked Apr 23 '26 02:04

The50


1 Answers

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

like image 145
Melcma Avatar answered Apr 25 '26 16:04

Melcma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!