crop-image

How to crop image instead of resize css

There are many ways to crop the image according to your need but what if you are newbie and don’t have knowledge of Photoshop or it is not installed at your machine? Then tricks below about CSS To Crop an Image may come in handy in your developing life.

It is possible to apply fixed width and height to image to get the image with required dimension but the main drawback with this style is it will stretch the image to fit the box hence lead to a pixilated image, which looks ugly.

After taking into consideration of various methods i came up with three best ways:-

1. CSS To Crop Image with background positioning CSS

It is the first method to get the required result. This contains the use of background-position attribute.

Here I am providing the HTML code which is used as an example.

<div id="resize"></div>

Instead of using img attribute here in html you can use it as a background of the above div.

#resize{
    position: relative;
    width: 250px;
    height: 250px;
    display: block;
    background-image: url(http://techssl.com/images/demo-css-300x300.jpg);
    background-position: 55% 55%;
}

2.CSS To Crop Image with clip property of CSS

Clip property of CSS contains unique features as it reduces developer’s effort to a great extent.
It is supported by all major browsers like Firefox, Chrome, IE, Opera etc.
I will use the same html above to demonstrate it.

#resize{
    position: absolute;
    clip: rect(60px, 225px, 225px, 70px);
}

We’re using position absolute as clip can only be applied to a absolute or fixed positioned element. So remember to absolute position you element before applying clip property to any element. The need to position an element is biggest drawback of this property as it arises various box level problems but you can experiment further to rectify those.
The rect attribute describes the rectangular clipping and the four values define the offsets from top right bottom and left consecutively.

3.CSS To Crop Image by making overflow hidden

Crop the image by highlighting the required and making useless part hidden by using overflow property.
We are going to add image attribute to the above html as we are not going to use background property here.

<div id="resize">
<img src="http://techssl.com/images/demo-css-300x300.jpg"/>
</div>

CSS:-

#resize{ width: 512px; height: 320px; overflow: hidden; }
#resize img { width: 100%; }

The overflow: hidden makes the larger part of image than required hidden and hence it looks as if cropped. We are applying width property here to make the image fit to the size required if the image is smaller than the area cropped.
Keep experimenting as there are numerous ways with CSS To Crop Image.

About Eshwar Dubey

Leave a Reply

Your email address will not be published. Required fields are marked *