Home > Web Front-end > CSS Tutorial > How Can I Dynamically Set Background Images Using CSS Without JavaScript?

How Can I Dynamically Set Background Images Using CSS Without JavaScript?

Mary-Kate Olsen
Release: 2024-11-18 13:40:02
Original
460 people have browsed it

How Can I Dynamically Set Background Images Using CSS Without JavaScript?

Using CSS Variables to Dynamically Assign Background Images from HTML Data Attributes

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">
Copy after login

CSS:

.thumb {
    background-image: var(--background);
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template