Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dimension Independent Centred Images - This allows an image to be centered within a parent container of a fixed height no matter what height or width the child image is. http://jsfiddle.net/jamessouth/JpCXX/
/*
* 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%;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment