Sometimes you need to clip an image to a certain height, even though the image may be taller. Except when you do this, you end up getting only the top or bottom portion of the image, which probably isn’t useful.
Here’s how you vertically align the image inside of a clipping window.
Here’s an example
This is a 600px
image clipped to a 100px
high wrapper. I added some visual lines to help you see the center. You can click it to see the full original image.
<div class="image-wrapper">
<img class="zoom-image js-zoom-image" src="http://jonrohan.codes/assets/images/posts/centering.png"/>
</div>
Calculating the offset
This is tricky because you need to calculate the amount of vertical offset based on the height of the image and the height of the wrapper. For example this image is 600px
and the window is 100px
(600 - 100) / 2 = 250px
. We’ll need to bump image up vertically 250px
It is impractical to calculate for all your images, or costly to use JavaScript.
If we use some algebra to move our equation around, we end up with a * 0.5 + b * -0.5
where a = wrapper height
and b = image height
.
A fist full of properties
The two properties that we use to compute this dynamically is top
and translate
.
-
top
top calculates based on the wrapper. If we’re moving the
img { top: 50%; }
it moves the image down 50% of the wrapper height. -
translateY
translateY calculates based on the height of the object. When we’re applying it to the
img { transform: translateY(-50%); }
That moves the image back up, 50% of the image height.
Putting it together we get this css. We also need to set the position: relative;
on the img and overflow: hidden;
on the parent wrapper. Or we’ll end up seeing all the image anyways.
.image-wrapper {
height: 100px;
overflow: hidden;
}
.image-wrapper img {
position: relative;
top: 50%;
transform: translateY(-50%);
}
Oh and if you’re not using autoprefixer, which I highly recommend you put it in your workflow somewhere, then here are the browser prefixes you’ll need.
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
Practical example
I threw together an example on codepen. The example is similar to an image reveal you might find in a social timeline. Click the photo to see more of the image.
See the Pen Vertically center image by Jon Rohan (@jonrohan) on CodePen.
Support for CSS3 2D Transforms
IE | Firefox | Chrome | Safari | Android | iOS |
---|---|---|---|---|---|
9+ | 3.5+ | 4+ | 3.1+ | 2.1+ | 3.2+ |