There was a popular article written a few weeks ago called “Vertical align anything with just 3 lines of CSS“. This approach to vertically aligning things with top and translateY is something we’ve used recently, but in a little different context. We had to fit images into responsive containers that had fluid widths and set heights , and all we knew were the widths of the images.

Explore CSS Courses

This is how we did it

We took a mobile first approach, and used both translateY and translateX to keep the image centered at all times. This works in IE9 and up, but the fallback is pretty simple.

So to get started, we first created the container that the image was going to live in.

Quick note: we’re using Compass @include s for CSS3 properties

<div class="img-contain"></div>

.img-contain { width: 50%; height: 15em; margin: 0 auto; overflow: hidden; }

Then threw in an image.

<div class="img-contain"> <img class="img" src="https://placekitten.com/800/500"> </div>

And started in with the magical transform property, using the translateX value.

.img { position: relative; left: 50%; @include translateX(-50%); max-height: 100%; }

This positioned our image horizontally (not vertically quite yet) within the container. There comes a point, though, where the width of the container becomes wider than the width of the image, which leaves an unwanted gap to the left and right of the image. Since we always want our image to take up the full space of the container, we have to switch gears at a certain breakpoint and set the image’s width to 100% and start the vertical centering.

.img { position: relative; left: 50%; @include translateX(-50%); max-height: 100%; @media (min-width: 800px) { left: 0; // set the left back to 0 max-height: none; // remove the max-height max-width: 100%; @include translateY(-50%); } }

How did we come up with 800px as our breakpoint? Because that’s the width of the source image. In order to place the breakpoint correctly, you’ll have to know the width .

Explore Web Development Courses

Fallback

IE8 will not get the “centered” treatment without some pretty in-depth calculations to determine the aspect ratio. Without getting into that, all you know need to do to make the images at least take up the entire container is, either by detecting older browsers with Modernizr or using an IE8 stylesheet, set margin-left: -50% on the image and then margin-left: 0; margin-top: -50% on the image inside the media query.

You can see a demo of the technique over on CodePen.

Explore CSS Courses