Search code examples
javascripthtmlcssdynamiccenter

Center image grid on page containing left aligned images


I have a div that just contains a bunch of 145px X 145px thumbnail images. The div doesn't have a set width so that there is the highest amount of images in one row that your browser window can fit. Now I want to center that div container, but keep the images left aligned. So I can't use text-align: center, because if the last row has fewer images in it, that row will be centered under the rest of the rows. Is there a way to center the container div with css or do I have to use javascript?

I have a jsbin here: http://jsbin.com/eTukegu/3/edit

(I just put 7 thumbnails in for the example, and I used divs instead of images)

<div id="thumbnail_container">
  <div class="thumbnail"></div>
  <div class="thumbnail"></div>
  <div class="thumbnail"></div>
  <div class="thumbnail"></div>
  <div class="thumbnail"></div>
  <div class="thumbnail"></div>
  <div class="thumbnail"></div>
</div>

CSS:

#thumbnail_container
{
  margin: 5px;
  padding: 0;
}

.thumbnail
{
  width: 145px;
  height: 145px;
  background-color: #fff;
  display: inline-block;
  margin: 5px 1px 1px 5px;
  padding: 0;
}

Solution

  • This is the javascript I wrote to solve this: (my thumbnail images are 145x145 with 10px in between each thumbnail)

    window.onload = function()
    {
        setNewWidth();
    };
    
    window.onresize = function ()
    {
        setNewWidth();
    };
    
    function setNewWidth()
    {
        var containerWrapper = document.getElementById('thumbnail_container_wrapper');
        var containerWrapperWidth = containerWrapper.offsetWidth;
        var boxesInRow = Math.floor((containerWrapperWidth - 10) / 155);
        var newWidth = boxesInRow * 155;
        var container = document.getElementById('thumbnail_container');
        container.style.width = newWidth + "px";
    }