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)?
an nice alternative to
data-
attributes (or theattr()
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.
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 inlinestyle
attribute of the HTML element?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.As of writing, the browser support of
attr()
notation on CSS properties other thancontent
- likebackground-image
- is very limited.Besides, as per CSS level 2 spec, combining
url()
andattr()
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:
In your HTML:
In your CSS:
Problems:
Solution:
References:
Thanks: