I have created a jsFiddle for the code: http://jsfiddle.net/kinthof/QpjnV/3/
The code is as follows:
HTML:
<div class="image-container">
<img src="http://skafte.dk/img/oel/carlsberg-pilsner-33cl-51x192.jpg" class="" title="Carlsberg Pilsner 33cl" alt="Carlsberg Pilsner 33cl" />
<img src="http://skafte.dk/img/sodavand/faxe-kondi-25cl-54x192.jpg" class="" title="Faxe Kondi 25cl" alt="Faxe Kondi 25cl" />
<img src="http://skafte.dk/img/sodavand/coca-cola-25cl-50x192.jpg" class="" title="Coca Cola 25cl" alt="Coca Cola 25cl" />
<img src="http://skafte.dk/img/sodavand/frem-aeblemost-25cl-56x191.jpg" class="" title="Frem Æblemost 25cl" alt="Frem Æblemost 25cl" />
<img src="http://skafte.dk/img/diverse/cocio-40cl-58x192.jpg" class="" title="Cocio 40cl" alt="Cocio 40cl" />
<img src="http://skafte.dk/img/kildevand/aquador-50cl-54x191.jpg" class="" title="Aquador Kildevand 50cl" alt="Aquador Kildevand 50cl" />
</div>
CSS:
.image-container {
margin: 0 auto;
clear: both;
}
.image-container img {
display: block;
margin: 0 auto;
float: left;
}
jQuery:
/* Finding the images width and setting the container to the sum of the widths. */
$('.image-container').each(function () {
var width = 0;
$(this).find('img').each(function () {
width += $(this).width();
})
$(this).width(width + 'px');
});
/* Setting width to 100% if the width is larger than the viewport */
$('.image-container').each(function () {
var vpWidth = document.documentElement.clientWidth;
var imageContainerWidth = $(this).width();
var numberOfElements = 0;
if (imageContainerWidth > vpWidth) {
$(".image-container").width('100%');
}
});
I want to center the floated images. This is done in the first part where I find the images width and set the container to the sum of the widths, which I then center with CSS.
The purpose next is that if the viewport is smaller than the width of the .image-container then the .image-containers width sets to 100%.
But this only happens when the page is reloaded/updated.
My question is: How can this be done "live", so the width changes as I minimize the window?