CSS set background-image by data-image attr

Hossain Khademian picture Hossain Khademian · Nov 17, 2014 · Viewed 55.9k times · Source

I have sort of elements with this pattern:

<div data-image="{imageurl}" ...></div>

I want to set this elements background-image to data-image. I test this CSS code:

div[data-image] {
    border: 2px solid black;
    background-image: attr(data-image url);
}

border show correctly but nothing happened for background How can do I fix this code only with css (not js or jq)?

Answer

Eliran Malka picture Eliran Malka · Mar 20, 2019

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>