Centered Image
True centered image in a constrained parent container.
by jamessouth
HTML
<div class="parent">
<img src="http://placehold.it/1000x1000"/>
</div>
<div class="parent">
<img src="http://placehold.it/1000x10000"/>
</div>
CSS
/*
* Just there to add a little padding.
*/
body {
width:100%;
height:20000px;
padding: 100px;
}
/*
* Just here to add some spacing.
*/
div {
margin-bottom: 50px;
}
/*
* 1: Arbitrary width.
*/
.parent {
position: relative;
height: 250px;
max-width: 400px; /* 1 */
overflow: hidden;
}
/*
* Position the image absolutely and then move it's four positions
* 1000000% out of the container. This with an auto margin is the core of the trick.
* Why such a large number? Firefox seems to have issue when using larger images even
* at 100%.
*/
.parent img {
position: absolute;
top: -1000000%;
right: -1000000%;
bottom: -1000000%;
left: -1000000%;
margin: auto;
max-width: 100%;
}