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>