Aligning image to center inside a smaller div

See: http://jsfiddle.net/thirtydot/x62nV/ (and without overflow: hidden to easily see the centering)

This will work in all browsers, with the possible exception of IE6.

For .imageContainer > span, the margin-left is derived from the width, and the width is an arbitrary number which controls the maximal image width that will be supported. You could set width: 10000px; margin-left: -4950px; to support really wide images, if required.

HTML:

<div class="imageContainer">
    <span><img src="http://dummyimage.com/100x100/f0f/fff" /></span>
</div>

CSS:

.imageContainer {
    border: 1px solid #444;
    overflow: hidden;
    width: 100px;
    height: 100px;
    margin: 15px;
    text-align: center;
}
.imageContainer > span {
    display: block;
    width: 1000px;
    margin-left: -450px; /* -(width-container width)/2 */
}
.imageContainer > span > img {
    display: inline-block;
}

Leave a Comment