ST80
ST80

Reputation: 3903

CSS setting background image with data attribute

This has probably been asked before, but is it possible to set the background image with css based on the data attribute?

I have this:

<div class="imageWrap" data-bigImage="someURl" data-smallImage="someUrl"></div>

and my CSS:

background-image: attr(data-bigImage url);
background-repeat: no-repeat;
background-size: cover;

I use these 2 sizes for an responsive solution, and the data attribute can be changed by an admin, so I cannot set a path to a specific file..

How can I solve this? Is there a non-javascript solution?

Upvotes: 1

Views: 1947

Answers (1)

DRGA
DRGA

Reputation: 169

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.

Upvotes: 2

Related Questions