Skip to content
Home » Web » CSS » CSS Crop Image

CSS Crop Image

Web designers usually remove the unwanted edge of images to make central objects look bigger and more focused by image processing softwares or au, it's called cropping. But sometimes, the images are intended to be kept intact as originals. Under such requirements, you can play the trick by CSS.

First of all, let's see an example of resizing, we can shrink an image into the pre-defined boundary.

<center>
  <div style="display: inline-block; border: 5px solid silver">
    <img src="path-to-image" style="vertical-align: middle; max-height: 200px; max-width: 200px;" />
  </div>
</center>

The output will be:


Steps to Crop Image

Next, we add some features on the styles to show cropping:

  1. Set larger max-height and max-width in the image.
  2. Add margin: -30px; to the style of the image, the negative value will make the edge overflow 30 pixels to outside.
  3. Add overflow: hidden; to the outer div, it will ignore the overflow.
<center>
  <div style="display: inline-block; border: 5px solid silver; overflow: hidden; ">
    <img src="path-to-image" style="vertical-align: middle; max-height: 200px; max-width: 200px; margin: -30px; />
  </div>
</center>

The output will be:


As you can see, the square size is smaller and the image looks like to be cropped. This is a kind of image cropping doesn't need to alter the image at all. We just played a trick on the image by adding some CSS attributes to make it look like cropped.

Please note that, the outer container of the image does not necessarily be a <div>, it could be various kinds of elements, such as <span>, <td> or <button>.

Leave a Reply

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