CSS set background-image by data-image attr

a nice alternative to data- attributes (or the attr() approach in general) can be the use of custom properties (MDN, csswg, css-tricks).

as their values are not restricted to strings, we can pass around any type that is allowed as a custom property value!

also, you get the benefit of updating these properties at runtime, with a swap of a stylesheet.

.kitten {
  width: 525px;
  height: 252px;
  background-image: var(--bg-image);
}
<div  class="kitten"
      style="--bg-image: url('http://placekitten.com/525/252');">
</div>

Leave a Comment