Home >Web Front-end >CSS Tutorial >How Can I Dynamically Set Background Images in CSS Using Data Attributes?
Many elements in your code follow the pattern:
You aim to set the background-image of these elements to the value stored in the data-image attribute, using pure CSS.
You attempted to use the following CSS code to achieve this:
div[data-image] { border: 2px solid black; background-image: attr(data-image url); }
While the border was correctly displayed, the background-image remained unaffected.
A viable alternative to using data attributes is to employ CSS custom properties. Since their values are not limited to strings, you can assign any valid type.
Additionally, custom properties allow you to update values dynamically through a stylesheet swap.
Here's how you can use custom properties to set the background-image:
.kitten { width: 525px; height: 252px; background-image: var(--bg-image); } <div>
In this example, the --bg-image property is defined in the stylesheet and assigned to the image URL. The style attribute on the div element sets the value of --bg-image using inline styling. This allows you to specify the background image for each individual element without modifying the stylesheet.
By leveraging custom properties, you gain flexibility and maintainability in setting background images through data attributes.
The above is the detailed content of How Can I Dynamically Set Background Images in CSS Using Data Attributes?. For more information, please follow other related articles on the PHP Chinese website!