Center and crop images with two lines of CSS

Cris Noble
Jan 23, 2015 · 3 min read

Bonus points for retina image support with an additional three lines

I love learning about CSS specs that I have never heard of, and Chris Nager’s introduction to object-fit was no exception. I cannot wait until we have acceptable support for the semantically sensical techniques he presented.

Some may say that an automagically cropped and centered image is the holy grail of hipster blogging platforms. Medium does it, the creator of ghost does it, I even remember New York Times one upping everyone this one time.

The object-fit approach is swell because it let’s you use an <img> tag to specify an image. Horray for semantics! However, if your customers use non-webkit browsers once in a while, you are going to need to fall back to non-semantic hacks. Enter the background-positioning rule. It is a common technique and a very well supported property (92.45% of global market share, unprefixed). People like social proof, so here, have a look at how Medium does it.

The technique is simple, just create a div, in whatever size and position you want.

That was easy. And so far, completely useless. Now for the two lines of code that make your cover image the envy of photojournalists the world over.

Hold on there, that was a cheap trick to get down to two lines. Let’s make it a bit more readable.

Okay three lines, not bad.

Try it out for yourself with this demo. Resize the viewport. Screw IE8.

Bonus Points

Now that we already have an non-semantic <div> which is really an image, how about we take it a step further and provide retina support… with pure CSS.

For the gritty details on pixel density media queries, refer to this handy guide on CSS Tricks.

The creative front-end dev will immediately apply this technique to @3x images, min-width media queries, etc. I say go for it.

Mountains plus space image courtesy of a flickr creative commons search, which was handily won by Tom Fear.

Cris Noble is a developer and partner at Kovalent, a San Diego based design and development studio. You can find out more about him at, fork his code on github, or follow him on Twitter @crisnoble.

Web Development

Making things on the internet.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store