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
- To crop an image to a square first, add a class attribute to that image.
- Add the same pixels of height and width to that class.
- 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:
Cropping background-image to square
- To crop a background-image first add the same pixels of height and width to that image.
- Add a background-size property with value
cover
. - 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;
}
If you don’t set background-position
to center the image looks like this.
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:
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%;}