Home > Web Front-end > CSS Tutorial > How to Dynamically Set CSS Background Images Using Data Attributes?

How to Dynamically Set CSS Background Images Using Data Attributes?

Barbara Streisand
Release: 2024-11-09 17:11:02
Original
202 people have browsed it

How to Dynamically Set CSS Background Images Using Data Attributes?

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!

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