Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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

This code isnt working, of course.

like image 765
Enrique Moreno Tent Avatar asked Jun 20 '12 10:06

Enrique Moreno Tent


People also ask

What is the attribute to set image as background in CSS?

The background-image property specifies an image to use as the background of an element. By default, the image is repeated so it covers the entire element.

Which attribute is used to set the background image?

The HTML <body> background Attribute is used to specify the background-image for the document.

Which is the attribute of CSS that allows you to set a picture as a background of the table that will cover the whole table background?

Table Background Image. Here's an example of adding a background image to your table by using the CSS background-image property. The background image in this example automatically repeats across the full width and height of the table.

Which table data attribute is used to add background image in a cell?

The background attribute is used to set the background image in the given table.


1 Answers

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.

like image 195
oezi Avatar answered Oct 27 '22 06:10

oezi