HTML Data-Attributes: Dynamically Setting CSS Background Images
The goal is to dynamically set the background image for elements based on a data attribute in HTML, specifically using .thumb elements to display thumbnails.
In the HTML structure, each thumbnail div has a data-image-src attribute that specifies the URL of the image:
Initially, the expectation was to set the CSS background image using the attr function:
However, this approach did not work. As an alternative solution, CSS Variables are introduced.
Using CSS Variables
CSS variables allow you to declare a variable and use it in your styles:
In the above HTML, the --background variable is set using the style attribute.
In the CSS, the background-image property now references the --background variable. This ensures that each .thumb element uses the URL specified in its corresponding data-image-src attribute as its background image.
Codepen Example
A dynamic example of this approach can be found at:
https://codepen.io/bruce13/pen/bJdoZW
The above is the detailed content of How to Dynamically Set CSS Background Images Using Data Attributes?. For more information, please follow other related articles on the PHP Chinese website!