Home >Web Front-end >CSS Tutorial >How Can I Use a Data Attribute to Set a CSS Background Image?

How Can I Use a Data Attribute to Set a CSS Background Image?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-08 09:39:12505browse

How Can I Use a Data Attribute to Set a CSS Background Image?

CSS background-image from data-image Attribute

In HTML, elements often have data attributes used to store additional information. Setting a background image to a data attribute's value can be achieved solely through CSS.

The Issue

The provided CSS code:

div[data-image] {
    border: 2px solid black;
    background-image: attr(data-image url);
}

fails to display the background image.

The Solution: Custom Properties

An alternative approach is to use CSS custom properties, which allow setting any type of value, including URLs.

.kitten {
  background-image: var(--bg-image);
}

Then, set the custom property in the element's style attribute:

<div class="kitten">

This approach allows dynamic updates of the background image through CSS changes or script interactions.

The above is the detailed content of How Can I Use a Data Attribute to Set a CSS Background Image?. 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