How to crop images(square,circle) in CSS

How to crop images(square,circle) in CSS

In this tutorial, we are going to learn about how to crop images to a square, circle in CSS.

This is the example image we are working.

Cropping image to a square

  1. To crop an image to a square first, add a class attribute to that image.
  2. Add the same pixels of height and width to that class.
  3. Then add an object-fit property with value cover so that the image fits perfectly to the given height and width.

Example:

<img src="https://images.unsplash.com/photo-1563805042-7684c019e1cb"
class="myimg" />
.myimg{
  width:300px;
  height:300px;
  object-fit:cover;
}

output:

crop-image-square

Cropping background-image to square

  1. To crop a background-image first add the same pixels of height and width to that image.
  2. Add a background-size property with value cover.
  3. At final set background-position property to center.

Example:

<div class="row"></div>
.row{
  width:300px;
  height:300px;
  background-image: url( https://images.unsplash.com/photo-1563805042-7684c019e1cb);
  background-size:cover;
  background-position:center;
}

Output: crop-image-square

If you don’t set background-position to center the image looks like this.

crop-background-image

Cropping image to a circle

We can crop an image to a circle by adding a border-radius property with value 50% to the square image.

Example:

  <img src="https://images.unsplash.com/photo-1563805042-7684c019e1cb"
    class="myimg" />
.myimg{
  width:300px;
  height:300px;
  object-fit:cover;
  border-radius:50%;}

Output:

crop-image-circle

Similarly, we can crop background-image to circle by adding border-radius value to 50%.

Example

.row{
  width:300px;
  height:300px;
  background-image: url( https://images.unsplash.com/photo-1563805042-7684c019e1cb);
  background-size:cover;
  background-position:center;
  border-radius:50%;}