Home >Web Front-end >CSS Tutorial >How to create dynamic image backgrounds with HTML data attributes and CSS variables?

How to create dynamic image backgrounds with HTML data attributes and CSS variables?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-09 17:31:02406browse

How to create dynamic image backgrounds with HTML data attributes and CSS variables?

Dynamic Image Backgrounds Using HTML Data Attributes and CSS

Problem:

Suppose you're creating a custom photo gallery and using HTML's data attributes to store image URLs. You want to assign these URLs to the background-image property of div elements representing thumbnails.

HTML Code:

<div class="thumb" data-image-src="images/img.jpg"></div>

CSS Code (Questionable Part):

.thumb {
    background-image: attr(data-image-src);
}

The objective is to extract the data-image-src value from each thumb div and set it as the background-image for that div in the CSS file.

Solution:

Using CSS variables allows you to achieve this without jQuery or browser-specific hacks. Note that CSS variables are not supported in Internet Explorer.

Updated HTML Code:

<div class="thumb">

Updated CSS Code:

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

Codepen Demo:

https://codepen.io/bruce13/pen/bJdoZW

The above is the detailed content of How to create dynamic image backgrounds with HTML data attributes and CSS variables?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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