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 HTMLBackground-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
It is not best practise to mix up content with style, but a solution could be
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).
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.
You will eventually be able to use
but that is not implemented anywhere yet to my knowledge. In the above,
url
is an optional "type-or-unit" parameter toattr()
. See https://drafts.csswg.org/css-values/#attr-notation.You will need a little JavaScript for that:
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.HTML
jQuery
Demo on JSFiddle
You could do this also with JavaScript.
HTML CODE
JS CODE