13

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?

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

This code isnt working, of course.

Scimonster
  • 32,893
  • 9
  • 77
  • 89
Enrique Moreno Tent
  • 24,127
  • 34
  • 104
  • 189
  • not with pure css, but with javascript - is this an option for you? – oezi Jun 20 '12 at 10:50
  • My goal was to get it with CSS – Enrique Moreno Tent Jun 20 '12 at 10:51
  • 5
    You're *supposed* to be able to do this with [the CSS3-enhanced version of `attr()`](http://www.w3.org/TR/css3-values/#attr) (except you need to quote the strings), but there are no known implementations. Your only way is to hardcode them as oezi suggests. – BoltClock Jun 20 '12 at 23:07

2 Answers2

13

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.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
oezi
  • 51,017
  • 10
  • 98
  • 115
1

I know the original question stressed doing it with just CSS, but I got to this question because another question (that wasn't necessarily asking for a CSS solution) was marked as a duplicate of this. Here's what I'm using as the solution, in case it helps anyone else, and it uses javascript w/jQuery:

$('.slide').each(function (index) {
    var slide = $(this);
    slide.css('background-image', 'url(' + slide.data('bg') + ')');
});
Nagisa
  • 83
  • 6