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!