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)?
The HTML <body> background Attribute is used to specify the background-image for the document. Note: It is not supported by HTML5 Instead of using this attribute we use CSS background property. Attribute Values: It contains the value i.e URL Which specify the address of the background Image.
The most common & simple way to add background image is using the background image attribute inside the <body> tag.
The background-image property sets one or more background images for an element. By default, a background-image is placed at the top-left corner of an element, and repeated both vertically and horizontally.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With