Home  >  Article  >  Web Front-end  >  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
Susan SarandonOriginal
2024-11-09 12:26:02563browse

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>

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 */
}

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">
.thumb {
    background-image: var(--background);
}

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!

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