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!