59

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

Hossain Khademian
  • 1,372
  • 3
  • 17
  • 27

4 Answers4

46

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>
Eliran Malka
  • 14,498
  • 5
  • 72
  • 96
37

As of writing, the browser support of attr() notation on CSS properties other than content - like background-image - is very limited.

Besides, as per CSS level 2 spec, combining url() and attr() is not valid:
content: url(attr(data-image));.

Hence there is no cross-browser CSS solution at the moment to achieve the desired result. Unless using JavaScript is an option:

var list = document.querySelectorAll("div[data-image]");

for (var i = 0; i < list.length; i++) {
  var url = list[i].getAttribute('data-image');
  list[i].style.backgroundImage="url('" + url + "')";
}
div[data-image] {
  width: 100px; height: 100px; /* If needed */
  border: 2px solid black;
}
<div data-image="http://placehold.it/100"></div>
Hashem Qolami
  • 88,138
  • 25
  • 132
  • 151
  • Limit yes, attir(data) works in most browser but the CSS3 version attr(data type fallback) are not supported. [See browser status for CSS3 attr](http://caniuse.com/#search=css3%20attr) – TheCrazyProfessor Mar 18 '17 at 14:14
18

In your HTML:

<div data-image="path_to_image/image_file.extension" ... ></div>

In your CSS:

div:after {
    background-image : attr(data-image url);
    /* other CSS styling */
}

Problems:

This is your required answer. Check this documentation in w3.org. But the main problem is it won't work, not yet!. In many browsers, attr() runs successfully when it is used in content: attribute of the CSS coding. But using it in other attributes of CSS, it doesn't work as expected, not even in major browsers.

Solution:

  • Use scripts such as JavaScript or jQuery.

References:

Thanks:

Community
  • 1
  • 1
cuSK
  • 806
  • 11
  • 23
  • 4
    Note that `url( attr(data-image) )` is *definitely* wrong. According to [CSS Values and Units Module Level 3](http://www.w3.org/TR/css3-values/#url), `url()` notation only accepts bare/quoted `` as URI. The OP has already used the valid syntax of `attr()`, but it is not implemented in browsers yet. – Hashem Qolami Nov 17 '14 at 09:19
  • 1
    @HashemQolami, thank you. But I didn't understand the documentation of url. What exactly will come in place of `url( attr() )`?? – cuSK Nov 17 '14 at 09:32
  • As I mentioned, the OP used the valid syntax: `attr(data-image url)` which is stated by [the spec](http://www.w3.org/TR/css3-values/#attr). The new syntax of `attr()` is: `attr( ? [ , ]? )` where optional `` specifies the type of the given `` and the `` would be the default value if named attribute is missing. – Hashem Qolami Nov 17 '14 at 09:38
  • 1
    @HashemQolami, thank you for your valuable help. I never learnt anything from documentations, everything I learn is from a person's teachings. But, I still include the links to documentation for clearing problems to questioners. – cuSK Nov 17 '14 at 16:44
  • What I meant was that such `attr()` usage remains unimplemented in the browsers, which is pity. – rr- Apr 11 '16 at 10:32
  • @rr- Yeah... People think that technology is growing fast, but we realize that it is growing too slow. :) – cuSK Apr 12 '16 at 05:11
  • 2
    I think `=` needs to be `:` in your CSS. – user2428118 Jun 17 '16 at 14:12
  • Seufs. I really hoped that this would work but alas. Pretty weird that attr() has been supported since forever (Chrome 2.0(!) for example) but only for 'content'. Who invented this? Tesla? Did any progress on this go down with him like all the other cool stuff he dreamed up? :( – REJH Mar 23 '17 at 16:59
  • Why it that not working "solution" has 18 votes up? – andfra Mar 14 '21 at 15:22
15

If the goal is being able to set the background-image style of an HTML element from within the HTML document rather than the CSS definition, why not use the inline style attribute of the HTML element?

div[style^='background-image'] {
  width:400px;
  height:225px;
  background-repeat:no-repeat;
  background-size:contain;
  background-position:center center;
  /* background-image is not set here... */
}
<!-- ... but here -->
<div style="background-image:url(http://img01.deviantart.net/5e4b/i/2015/112/c/5/mandelbrot_62____courage_to_leave___by_olbaid_st-d646sjv.jpg)"></div>

EDIT:

If selecting the <div> by style is not an option, you may be able to give it a class and select it by class name.

Carvo Loco
  • 1,859
  • 10
  • 17
  • 2
    This is a simple solution to the question without browser incombabilities and thus should be upvoted. – Joschi Nov 16 '17 at 13:38