Home >Web Front-end >CSS Tutorial >How Can I Dynamically Set Background Images Using CSS Without JavaScript?
Question:
How can CSS be utilized to automatically set the background image of elements based on values stored in HTML data attributes, without relying on JavaScript?
Answer:
CSS variables provide a solution to this issue. CSS variables allow styles to be customized dynamically based on values defined in HTML elements. Here's an example:
HTML:
<div class="thumb">
CSS:
.thumb { background-image: var(--background); }
Explanation:
In the HTML code, the style attribute is used to define a CSS variable named --background and assign it the URL of the desired background image. In the CSS code, the background-image property refers to the --background variable for its value.
When the page loads, the browser parses both the HTML and CSS code. It recognizes the CSS variable defined in the HTML and applies its value to the background-image property of elements with the .thumb class.
Codepen Demo:
https://codepen.io/bruce13/pen/bJdoZW
Note:
CSS variables are not supported in Internet Explorer. If supporting IE is required, alternative approaches may be necessary.
The above is the detailed content of How Can I Dynamically Set Background Images Using CSS Without JavaScript?. For more information, please follow other related articles on the PHP Chinese website!