OneBite.Dev - Coding blog in a bite size

crop image in css

Code snippet for how to crop image in css with sample and detail explanation

Cropping an image is a vital aspect in creating a visually appealing web page. This article will guide you through the process of cropping an image using CSS in an easy and simple way.

Code snippet for cropping an image in CSS

Here is an illustration of how to crop an image using CSS make use of:

img {
    object-fit: cover; 
    width: 300px;   
    height: 200px; 
}

In this code, an image is selected with the ‘img’ tag. The ‘object-fit: cover;’ line ensures that the image covers the size designated irrespective of its aspect ratio. The ‘width’ and ‘height’ properties then set the desired size of the image.

Code Explanation for Cropping an image in CSS

The first line of the code selects the image that you intend to crop using the ‘img’ tag:

img {

Next, ‘object-fit: cover;’ is used to ensure the image covers the entire width of the box, maintaining its aspect ratio, but having potential parts of the image cut off. In comparison to ‘object-fit: contain;’, which ensures the image fits into the box while showing the full image and potentially leaving blank spaces to the left & right or top & bottom.

    object-fit: cover;

In the subsequent lines, the ‘width: 300px;’ and ‘height: 200px;’ variables are used to set the dimension of the image box:

    width: 300px;   
    height: 200px;

In this situation, our image will fill up a box that is 300 pixels wide and 200 pixels tall. If the image isn’t exactly this size, parts of the image will be truncated due to the ‘object-fit: cover;’ property.

This simple method allows you to manipulate images to fit your design aesthetic, thereby ensuring that your website does not encounter displaying morphed or distorted images. By integrating the CSS Image Crop function in your skills set, you can creatively tweak your presents to fit diverse applications.

css