0

I'm trying to assign the url of background-image dynamically though css from the attributes defined on html tags. But it seems neither attr() nor var() works. I'm avoiding to use javascript because the url might change later so I have to trigger that script manually again.

Is there a better solution for this?

body {
  display: flex;
}

.normal, .attr, .var {
  flex: 1;
  height: 240px;
  border: solid 1px #666;
  background-size: cover;
}

.normal {
  background-image: url("https://picsum.photos/320/240");
}

.attr {
  background-image: url(attr(data-bg));
}

.var {
  background-image: url(var(--url));
}
<div class="normal"></div>
<div class="attr" data-bg="https://picsum.photos/320/240"></div>
<div class="var" style="--url: 'https://picsum.photos/320/240';"></div>

Even more, I wish I can concatenate the string if it's possible.

.image {
  border: solid 1px #666;
  width: 320px;
  height: 240px;
  /* I wish this is possible */
  background-image: url("http://www.example.com/images/" attr(data-bg) ".png");
}
<div class="image" data-bg="adorable_cat"></div>
Hao Wu
  • 17,573
  • 6
  • 28
  • 60

2 Answers2

3

Even if I feel like it would be much easier to do with simply using inline background-image property (especially if you want to concatenate url string). For simple use you can do that like that:

<div class="var" style="--url: url(https://picsum.photos/320/240)"></div>

.var {
  background-image: var(--url);
}

For reasons unclear for me, using url(var(--url)); doesn't seem to be working at all (at least at Chrome)

Adam Kosmala
  • 925
  • 6
  • 9
-1

Put an embedded stylesheet in the document's :

<style type="text/css">
.logo
{
background: #FFF url(<?php echo $variable_holding_img_url; ?>);
}
</style>

for more information

enter link description here

How to have dynamic image as CSS background?

Pradeep Kumar
  • 109
  • 1
  • 10