There are several ways to crop an image in CSS; however, the simplest and most effective of these are:
The object-fit CSS property can be used to easily crop images. It can have five values, but cover is the most suitable.
object-fit: cover;, the aspect ratio of the image is preserved while still fitting into the size of its content box.
object-fit property can be used in conjunction with
object-position to adjust the area of the image to crop. The
object-position property requires two values:
y% to position the image (the default position is
50% 50%). We can also provide pixel positions:
ypx, but that is usually not useful.
Consider this x pixel image of a puppy; it has been cropped using
object-fit and adjusted using
object-position. Experiment by changing its values and note the output:
Along with width and height, CSS containers also have an overflow property that can be used for image cropping. To activate the overflow property enclose the image, within a div of a particular width and height, and set
overflow:hidden. This will ensure that the base container will retain its structure, and any image overflow will be hidden behind the container.
Finally, the margin property is used on the image to adjust the cropped area. This property takes four values. However, only the first and last of the four values are essential as they represent the pixels from the top, and the left, respectively.
Consider the example below; it uses the same x image of a puppy. Experiment with the values of
margin, note the output:
View all Courses