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

Mary-Kate Olsen
Release: 2024-11-09 17:31:02
Original
360 people have browsed it

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

CSS Code (Questionable Part):

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

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

Updated CSS Code:

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

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!

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