CSS background-image from data-image Attribute
In HTML, elements often have data attributes used to store additional information. Setting a background image to a data attribute's value can be achieved solely through CSS.
The Issue
The provided CSS code:
div[data-image] { border: 2px solid black; background-image: attr(data-image url); }
fails to display the background image.
The Solution: Custom Properties
An alternative approach is to use CSS custom properties, which allow setting any type of value, including URLs.
.kitten { background-image: var(--bg-image); }
Then, set the custom property in the element's style attribute:
<div class="kitten">
This approach allows dynamic updates of the background image through CSS changes or script interactions.
The above is the detailed content of How Can I Use a Data Attribute to Set a CSS Background Image?. For more information, please follow other related articles on the PHP Chinese website!