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

How to Dynamically Set CSS Background-Image URL Using HTML Data-Attributes?

Susan Sarandon
Release: 2024-11-09 12:26:02
Original
619 people have browsed it

How to Dynamically Set CSS Background-Image URL Using HTML Data-Attributes?

Setting CSS Background-Image URL Using HTML Data-Attributes

Creating a custom photo gallery requires careful consideration of HTML structure and CSS. To determine the CSS background-image URL dynamically based on HTML data-attribute, we can leverage CSS variables.

HTML Thumb Format

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

CSS with CSS Variables

.thumb {
    --background: url(attr(data-image-src)); /* Store URL in CSS variable */
    
    background-image: var(--background); /* Use CSS variable for background image */
}
Copy after login

With this approach, the data-image-src from the div.thumb is stored in a CSS variable. Subsequently, the background-image property references the CSS variable to dynamically set the background image URL.

Browser Support
CSS variables are not supported in Internet Explorer, necessitating an alternative approach. For IE compatibility, a solution using CSS preprocessors or JavaScript is recommended.

Code Example

<div class="thumb">
Copy after login
.thumb {
    background-image: var(--background);
}
Copy after login

A CodePen example demonstrating this technique can be found here: https://codepen.io/bruce13/pen/bJdoZW

The above is the detailed content of How to Dynamically Set CSS Background-Image URL Using HTML 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