Architectural Blog, Modern Buildings & Casino Designs Loading...

“Cropping” images using simple CSS and JS

Recently I came across an interesting problem – I needed to be able to “crop” images that were brought across to my site dynamically, into square shapes. The problem was that the images were all varied in size and shape. I couldn’t work out a straight-up CSS way to do this, given that some pictures would be landscape and some would be portrait.

The idea was that I would have a container around the image the width and height I wanted the image to be, and then set the overflow to hidden and max-width to 100%, forcing the image to be the desired size and then trim off the excess with in the overflow.

My styles seemed to work fine for portrait images and images that were already square, but landscape images didn’t really work with the whole max-width thing I had going on. In the end it was really simple – all I had to do was use a tiny bit of jQuery to let me know if the images were landscape and then apply slightly different styles to those images.

You can see the example code over on jsFiddle. This is quite a simple example requires the with and height to be set manually.

Responsive version

Using the same basic idea you could have these be flexible/responsive using the padding percentage box-model trick.

See the example code on jsFiddle

You can use either, but the responsive version has more complicated CSS so if you aren’t going to need it you may as well use the simple version.