How to Crop Images by CSS

  • by
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:

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, it 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: 260px; max-width: 260px; margin: -30px; />
  </div>
</center>

The output will be:

As you can see, the square size does not change, but the central object looks bigger. This is a kind of cropping without altering 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 *