82

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

2
  • apply width and height for the same. Commented Nov 17, 2014 at 7:56
  • use custom properties? Commented Mar 20, 2019 at 21:21

4 Answers 4

94

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>

Sign up to request clarification or add additional context in comments.

8 Comments

This should be the accepted solution IMO. It allows you to set an attribute that the CSS can use to specify the background image. This is just using style instead of data-*. Very clever solution.
yeah but if you have a dynamic list, that won't work
where the output is generated in a for-loop, and the --bg-image is reset on every iteration to a new value
Very clever :) !
|
41

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>

1 Comment

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
23

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:

10 Comments

Note that url( attr(data-image) ) is definitely wrong. According to CSS Values and Units Module Level 3, url() notation only accepts bare/quoted <string> as URI. The OP has already used the valid syntax of attr(), but it is not implemented in browsers yet.
@HashemQolami, thank you. But I didn't understand the documentation of url. What exactly will come in place of url( attr() )??
As I mentioned, the OP used the valid syntax: attr(data-image url) which is stated by the spec. The new syntax of attr() is: attr( <attr-name> <type-or-unit>? [ , <fallback> ]? ) where optional <type-or-unit> specifies the type of the given <attr-name> and the <fallback> would be the default value if named attribute is missing.
@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.
I think = needs to be : in your CSS.
|
20

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.

1 Comment

This is a simple solution to the question without browser incombabilities and thus should be upvoted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.