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

Tags: css,css3,custom-data-attribute

Problem :

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.

Solution :

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.

    CSS Howto..

    How to attribute different ids to child elements depending on the number of parent-like elements in that container

    How to change select element's background color when it's selected?

    How to create a texture paper background using CSS without image

    Bootstrap “jumbotron-narrow” example. how does the style change?

    How to apply css on checkbox when it's getting disabled?

    How to use CSS in XML and XSL

    How to set css via jquery for preventing some action

    I'm am trying to have a responsive navigation bar for small screens, how can I change the left links to a css drop-down menu?

    How to solve CSS -webkit-appearance issue

    Hide/Show Content at Specific Scroll Positions

    How to change the css color code permanent using php

    How to force html element click wireup from js in dynamically loaded page

    How to sort properties in CSS file by groups?

    How can i place a child div on a fixed position of a parent div that when i change place of parent then child should move automatically?

    How to Prevent Opacity for Sub Div using Jquery

    How to positioning the tooltip above cursor

    how to layout tictactoe with html and css on a webpage

    How to temporarily add a CSS style?

    How to draw a line with css and show text or image on it

    css how to get rounded corners on button.

    How to properly align a page with header, nav, section and footer // HTML5 and CSS

    How to indent text like in a table, but without a table?

    How to add a value in the y-axis at the bottom of a bar chart-css

    How to set % height in fluid layout?

    How does reveal.js resize elements?

    CSS/PHP: How to make the next div appear on the side instead

    How to make a white square around my form fields?

    DropDown Menu won't show for more than a second..not working.

    How do I make a play button for my full page video?

    How to add CSS class to the HTML5 picture element