I am looking for a way to dynamically assign the url
of the background-image
through CSS based on attributes defined in HTML tags. I have tried using both attr()
and var()
, but neither seem to work. I prefer not to use JavaScript as the URL may change later, requiring manual script triggering.
Is there a more effective solution to achieve 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>
In addition, I would like to be able to concatenate strings if 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>