Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS set background-image by data-image attr

I have sort of elements with this pattern:

<div data-image="{imageurl}" ...></div> 

I want to set this elements background-image to data-image. I test this CSS code:

div[data-image] {     border: 2px solid black;     background-image: attr(data-image url); } 

border show correctly but nothing happened for background How can do I fix this code only with css (not js or jq)?

like image 791
Hossain Khademian Avatar asked Nov 17 '14 07:11

Hossain Khademian


People also ask

Is background image an attribute?

The HTML <body> background Attribute is used to specify the background-image for the document. Note: It is not supported by HTML5 Instead of using this attribute we use CSS background property. Attribute Values: It contains the value i.e URL Which specify the address of the background Image.

Which attribute should be used to set image as background?

The most common & simple way to add background image is using the background image attribute inside the <body> tag.

How can we set the image as background property?

The background-image property sets one or more background images for an element. By default, a background-image is placed at the top-left corner of an element, and repeated both vertically and horizontally.


1 Answers

a nice alternative to data- attributes (or the attr() approach in general) can be the use of custom properties (MDN, csswg, css-tricks).

as their values are not restricted to strings, we can pass around any type that is allowed as a custom property value!

also, you get the benefit of updating these properties at runtime, with a swap of a stylesheet.

.kitten {    width: 525px;    height: 252px;    background-image: var(--bg-image);  }
<div  class="kitten"        style="--bg-image: url('http://placekitten.com/525/252');">  </div>
like image 95
Eliran Malka Avatar answered Oct 06 '22 11:10

Eliran Malka