A responsive approach to image scaling with CSS

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 @includes for CSS3 properties

Then threw in an image.

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

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.

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


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

Kyle Pennell
Kyle Pennell is a marketer and writer with a variety of technical chops (JavaScript, Google Sheets/Excel, WordPress, SEO). He loves clear and helpful copy and likes automating things and making web apps (mostly maps). Found at kyleapennall.com and many other digital spaces