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.

Leave a Comment