[css] Using HTML data-attribute to set CSS background-image url

I plan on building a custom photo gallery for a friend and I know exactly how I am going to be producing the HTML, however I am running into a small issue with the CSS.
(I would prefer to not have the page styling rely on jQuery if possible)


My question regards:
Data-Attribute in HTML
Background-image in CSS
I am using this format for my html thumbnails:
<div class="thumb" data-image-src="images/img.jpg"></div>

and I assume the CSS should look something like this:

.thumb {
    width:150px;
    height:150px;
    background-position:center center;
    overflow:hidden;
    border:1px solid black;

    background-image: attr(data-image-src);/*This is the question piece*/
}


My goal is to take the data-image-src from the div.thumb in my HTML file and use it for each div.thumb(s) background-image source in my CSS file.

Here is a Codepen Pen in order to get a dynamic example of what I am looking for:
http://codepen.io/thestevekelzer/pen/rEDJv

This question is related to css background-image custom-data-attribute

The answer is


You will eventually be able to use

background-image: attr(data-image-src url);

but that is not implemented anywhere yet to my knowledge. In the above, url is an optional "type-or-unit" parameter to attr(). See https://drafts.csswg.org/css-values/#attr-notation.


For those who want a dumb down answer like me

Something like how to steps as 1, 2, 3

Here it is what I did

First create the HTML markup

<div class="thumb" data-image-src="images/img.jpg"></div>

Then before your ending body tag, add this script

I included the ending body on the code below as an example

So becareful when you copy

<script>
var list = document.getElementsByClassName('thumb');

for (var i = 0; i < list.length; i++) {
  var src = list[i].getAttribute('data-image-src');
  list[i].style.backgroundImage="url('" + src + "')";
}
</script>

</body>

It is not best practise to mix up content with style, but a solution could be

<div class="thumb" style="background-image: url('images/img.jpg')"></div>

You will need a little JavaScript for that:

var list = document.getElementsByClassName('thumb');

for (var i = 0; i < list.length; i++) {
  var src = list[i].getAttribute('data-image-src');
  list[i].style.backgroundImage="url('" + src + "')";
}

Wrap that in <script> tags at the bottom just before the </body> tag or wrap in a function that you call once the page loaded.


How about using some Sass? Here's what I did to achieve something like this (although note that you have to create a Sass list for each of the data-attributes).

/*
  Iterate over list and use "data-social" to put in the appropriate background-image.
*/
$social: "fb", "twitter", "youtube";

@each $i in $social {
  [data-social="#{$i}"] {
    background: url('#{$image-path}/icons/#{$i}.svg') no-repeat 0 0;
    background-size: cover; // Only seems to work if placed below background property
  }
}

Essentially, you list all of your data attribute values. Then use Sass @each to iterate through and select all the data-attributes in the HTML. Then, bring in the iterator variable and have it match up to a filename.

Anyway, as I said, you have to list all of the values, then make sure that your filenames incorporate the values in your list.


HTML CODE

<div id="borderLoader"  data-height="230px" data-color="lightgrey" data- 
width="230px" data-image="https://fiverr- res.cloudinary.com/t_profile_thumb,q_auto,f_auto/attachments/profile/photo/a54f24b2ab6f377ea269863cbf556c12-619447411516923848661/913d6cc9-3d3c-4884-ac6e-4c2d58ee4d6a.jpg">

</div>

JS CODE

var dataValue, dataSet,key;
dataValue = document.getElementById('borderLoader');
//data set contains all the dataset that you are to style the shape;
dataSet ={ 
   "height":dataValue.dataset.height,
   "width":dataValue.dataset.width,
   "color":dataValue.dataset.color,
   "imageBg":dataValue.dataset.image
};

dataValue.style.height = dataSet.height;
dataValue.style.width = dataSet.width;
dataValue.style.background = "#f3f3f3 url("+dataSet.imageBg+") no-repeat 
center";

If you wanted to keep it with just HTML and CSS you can use CSS Variables. Keep in mind, css variables aren't supported in IE.

<div class="thumb" style="--background: url('images/img.jpg')"></div> 
.thumb {
    background-image: var(--background);
}

Codepen: https://codepen.io/bruce13/pen/bJdoZW


HTML

<div class="thumb" data-image-src="img/image.png">

jQuery

$( ".thumb" ).each(function() {
  var attr = $(this).attr('data-image-src');

  if (typeof attr !== typeof undefined && attr !== false) {
      $(this).css('background', 'url('+attr+')');
  }

});

Demo on JSFiddle

You could do this also with JavaScript.


Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to background-image

How to add a color overlay to a background image? CSS: stretching background image to 100% width and height of screen? CSS blur on background image but not on content Adding background image to div using CSS How to apply a CSS filter to a background image How to use responsive background image in css3 in bootstrap Responsive background image in div full width Overlay a background-image with an rgba background-color Is there a way to set background-image as a base64 encoded image? Using HTML data-attribute to set CSS background-image url

Examples related to custom-data-attribute

How can I get the values of data attributes in JavaScript code? jQuery: get data attribute jQuery find element by data attribute value Using HTML data-attribute to set CSS background-image url Adding data attribute to DOM Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error? How to set data attributes in HTML elements jQuery Data vs Attr? Unable to set data attribute using jQuery Data() API Select elements by attribute in CSS