Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using HTML data-attribute to set CSS background-image url

People also ask

Can you make a background image a link?

You can't. Background images are not part of the HTML; they are part of the CSS. To make images clickable aka hyperlinked you need to insert them into your HTML.

Which attributes used to set the background image?

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

How do I add a background image to a specific section in HTML?

To insert an image in HTML, use the image tag and include a source and alt attribute. Like any other HTML element, you'll add images to the body section of your HTML file. The HTML image element is an “empty element,” meaning it does not have a closing tag.


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.


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


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.