Center and crop images with two lines of CSS

Cris Noble
Web Development
3 min readJan 23, 2015

--

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.

Inspecting Medium’s CSS rules

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

<!-- markup -->
<div class="cover-image"></div>
.../** CSS **/
.cover-image {
width: 100%;
height: 600px;
position: absolute;
top: 0;
left: 0;
}

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.

.cover-image {
/* rules from above, plus... */
background: url('/images/mountains-and-space.jpg') center;
background-size: cover;
}

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

.cover-image {
/* rules from above, plus... */
background-image: url('/images/mountains-and-space.jpg');
background-position: center;
background-size: cover;
}

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.

@media (-webkit-min-device-pixel-ratio: 1.5), (min-resolution: 1.5dppx) {
.cover-image {
background-image: url('/images/mountains-plus-space@2x.jpg');
}
}

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 crisnoble.com, fork his code on github, or follow him on Twitter @crisnoble.

--

--