Reputation: 3904
I have tons of same divs. Each has his own background.
<div class="grid-item"><div class="grid-con" style="background:url(http://image-goes-here.com/img.jpg);"></div></div>
// etc...
I am using jQuery to set properties to background:
$(".grid-con").css({"background-size": "100% auto", "background-repeat": "no-repeat", "background-position": "50% 50%"});
And css for extra properties:
.masonry { float:left; width:950px; margin-top:20px; }
.grid { width:100%; }
.grid-item { width:217px; margin:0 20px 20px 0; }
.grid-con { width:100%; height:auto; }
Everything works fine, if i set fixed height to .grid-con
.
Question:
How to make it work without fixed height? width:100%
works perfect, but height:auto
does not. I need to display all backgrounds which needs to fit fixed width with unknown height.
Upvotes: 1
Views: 75
Reputation: 86423
I'm not sure if the results of this demo are what you're expecting, but here is the code:
$('.grid-con[style*=url]').each(function(){
var $this = $(this),
img = new Image(),
src = $this.attr('style').match(/url\(([^)]+)/);
if ( src && src.length >= 1 ) {
img.src = src[1];
$this.height(img.height);
}
});
You could also use the naturalHeight
of the image if you're not supporting IE8 or older (ref).
Upvotes: 1