Centering floating list items <li> inside a div or their <ul>

Sam picture Sam · Jun 4, 2011 · Viewed 25.2k times · Source

HTML:

<div class="imgcontainer">
    <ul>
            <li><img src="1.jpg" alt="" /></li>
            <li><img src="2.jpg" alt="" /></li>
            .....
    </ul>
</div>  

I'm coding a simple gallery page by creating unordered list and each list item of it contains an image.

    ul li {
        float: left;
    }

I set the width of the container as "max-width" so I can make possible to fit the list items (images) to the browser width.. meaning that they will be re-arranged when the browser window re-sized.

    .imgcontainer{
        max-width: 750px;
    }

Now the problem is those images or list items are not aligned to center, they are aligned to the left of .imgcontainer body (colored gray in the attached link below), leaving a space on the right when the window re-sized!

enter image description here

How can I center those images every time the window resized?

Here's the whole page/code you can preview it or edit it at JS Bin

http://jsbin.com/etiso5

Answer

Midas picture Midas · Jun 4, 2011

Remove float:left and use display:inline so that you can use text-align:center. Set the font size to zero so that you don't have white-space between the images.

ul {
    font-size:0;
    text-align:center
}
ul li {
    display:inline;
    zoom:1
}
.imgcontainer {
    max-width:750px;
    margin:0 auto
}

The zoom is a hack for old IE versions. This is however not a valid CSS property, so won't go through the W3C validator.