Dbugger Dbugger - 1 month ago 15
CSS Question

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

I have a folder with a few background images (one.jpg, two.jpg, three.jpg) , and this markup

<section class="slide" data-bg="one"></section>
<section class="slide" data-bg="two"></section>
<section class="slide" data-bg="three"></section>

Would it be possible somehow just with CSS to do something like this?

background-image: url(img/attr(data-bg).jpg);

This code isnt working, of course.


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

  background-image: url('img/one.jpg');
  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.