Search code examples
htmlcsscss-variables

How to assign background-image url dynamically with only html and css?


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>


Solution

  • 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)