Skip to content

Instantly share code, notes, and snippets.

@dborsatto
Created August 10, 2016 09:23
Show Gist options
  • Save dborsatto/e5cdf6782183fe77a517051be45e8f4c to your computer and use it in GitHub Desktop.
Save dborsatto/e5cdf6782183fe77a517051be45e8f4c to your computer and use it in GitHub Desktop.
Center position an image without altering its form factor
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
.image-container {
/**
* For this trick to work, you need to have some sort
* of size set to the container element.
*/
height: 500px;
width: 500px;
/**
* This is needed because a slight portion of the image
* will overflow from the container, and we should hide it.
*/
overflow: hidden;
/**
* This is needed so position: absolute for the child element
* will work as expected.
*/
position: relative;
}
.image-container img {
display: block;
/**
* Set with and height to auto,
* so it will retain its form factor.
*/
height: auto;
width: auto;
/**
* Set min-height and min-width to cover all container,
* I usually set it to 105% rather than 100% to avoid possible
* issues due to sub-pixel rendering.
*/
min-height: 105%;
min-width: 105%;
/**
* Optionally set max-height and max-width if you suspect
* you may work with images bigger than the container.
* If the container is rectangular, set the biggest element
* (height or width) to match its min-* counterpart,
* and omit the other attribute.
*/
max-height: 120%;
max-width: 120%;
/**
* Neat trick to center an element to its container.
* Values of "left" and "top" refer to the container,
* whereas those in "translate" refer to the element itself.
* This means you're pushing the top left corner of the image
* to the center of the element, and then you're moving it back
* exactly by half its size. Therefore the center of the image
* will always be at the center of the container.
*/
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="image-container">
<img src=".." alt="" />
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment