Felix Felix - 1 year ago 67
CSS Question

CSS crop a image to a square

I want to crop a image with a random size to a square aspect ratio. I just wanna use CSS and want it to be responsive and adapt the witdth and height automatically.

The css clip function does not work with percentages. (I'm using bootstrap grid)

Are there any other methods?

Thanks for your help and hints

Answer Source

You can use a background-image to accomplish this, with the cover background-size.


In the demo I am using an image with rectangular dimensions(400x200) but the div element has a height and width of 200px.

By using the cover value you maintain the original aspect ratio of the image and cover the visible area of the element, essentially cropping the image.

div {
  background: #2a2828 url("http://lorempixel.com/400/200/") no-repeat center center/cover;
  height: 200px;
  width: 200px;