Blog

CSS scalable image crop

By:
on:

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:

 

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?

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

There's no need to use a percentage; a fixed padding (for example 150px) works as well.

However, when you're making a responsive website, and in my opinion a website should always be responsive, I strongly advise using percentages.

Good luck!

KOEN IS HAPPY TO INTRODUCE APPSALOON
APPSALOON BV
Bampslaan 21 box 3.01
3500 Hasselt
Belgium
VAT: BE08 4029 5063
2021 © AppSaloon All Rights Reserved
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram