How to Use a Data Attribute to Set a Background-Image in CSS

Using HTML data-attribute to set CSS background-image url

You will eventually be able to use

background-image: attr(data-image-src url);

but that is not implemented anywhere yet to my knowledge. In the above, url is an optional "type-or-unit" parameter to attr(). See https://drafts.csswg.org/css-values/#attr-notation.

How can I use a data attribute to set a background-image in CSS?

This won't be possible with pure css unless you're doing it the "undynamic" way:

.slide[data-bg="one"]{
background-image: url('img/one.jpg');
}
.slide[data-bg="two"]{
background-image: url('img/two.jpg');
}
...

Maybe you can dynamically create that stylesheet from your filenames on server-side.

Another (likely easier) possibility is to do this with JavaScript - but since you excluded that I assume you know about that and just don't want to use it.

CSS setting background image with data attribute

I don't think it can be done the way you want to.
What you could do is create two child div's, and toggle between them.

<div class="imageWrap">
<div class="bigImage" style="background-image:url('someUrl');"></div>
<div class="smallImage" style="background-image:url('someUrl');"></div>
</div>

The CSS would then look something like this:

.imageWrap .bigImage,
.imageWrap .smallImage{
width:100%;
height:100%;
background-repeat:no-repeat;
background-position:center center;
background-size:cover;
display:block;
}
.imageWrap .smallImage{
display:none;
}

@media screen and (max-width:sizeInPx){
.imageWrap .smallImage{
display:block;
}
.imageWrap .largeImage{
display:none;
}
}

I would however prefer a javascript solution, since that wouldn't require me to preload / buffer two images.

How to use DATA ATTRIBUTE to add background image to an anchor tag with HTML and CSS

Did you try:

li a[data-value='ENGLISH']{
...
}
li a[data-value='FRENCH']{
...
}

How to set image with :before and data attribute with css

While there is a strong call for this from many developers, currently you cannot use attributes for URLs.

An alternative is to use CSS custom properties:

<li style="--image: url(https://via.placeholder.com/150/0000FF);">hello 1</li>
  /* your code … */
li:before {
background: var(--image);
}

Browser support is good, but you might want to weigh this option, versus simply inlining the background-image property and using a hidden background trick on the element itself:

<li style="background-image: url(https://via.placeholder.com/150/0000FF);">hello 1</li>
  /* your code … */
li { background-size: 0 0; }
li:before {
background-image: inherit;
}


Related Topics



Leave a reply



Submit