CSS scalable image crop

Ever needed an easy way to crop images with CSS, plus keeping them scalable?

Well here’s how I do it.

Let’s say you’re making a news website with a responsive grid filled with posts.

You don’t want your images being all different sizes because it makes your page look messy.

We want our website to look nice and clean.

This is our HTML, just simple:


<div class="crop">

    <img src="...">

</div>

So all the rest will be done just using CSS:


.crop {

    width: 100%;

    overflow: hidden;

    position: relative;

}

.crop::before {

    content: "";

    display: block;

    padding-top: 56%;

}

.crop img {

    display: block;

    width: 100%;

    height: auto;

    position: absolute;

    top: 0;

    left: 0;

}

As you can see I’m using the ‘::before’ selector to determine my DIVs height, just by using the padding. Don’t forget to add the ‘content’ property, even when it’s empty, without it the ‘::before’ selector won’t work.

I’m also using a percentage for the padding, why?

Because this way I can give all of my images the same aspect ratio, in this case 16:9.

You don’t need to use a percentage, a fixed padding (for example 150px) works as well.

But when you’re making a responsive website, and in my opinion a website should be responsive, I strongly advice using percentages.

Good luck!