Cropping an image in HTML

Take a look at the image of the Grails in Action book cover in the sidebar. That image has a white border to the right and bottom, but that border is not visible. Don’t believe me? Tough. For those of you who do believe me and want to know how to crop an image, read on.

The original image is 150×188, but to eliminate the white border we need to display 141×176, i.e. cut of the right 9 pixels and the bottom 12. We could use the width and height attributes of the img tag, but that doesn’t achieve what we want: the browser will just scale the image to fit in those dimensions, so the white border will still be visible.

The trick is to wrap the image in a div with the appropriate dimensions:

<div style="width: 141px; height: 176px; overflow: hidden">
  <img src="..." width="150" height="176">

Voila! The image is cropped! If I learn how to crop the left and top as well, I’ll update the post.

8 thoughts on “Cropping an image in HTML

  1. observer

    This appears to work for Internet Explorer, the technique above scales an image in Firefox instead of cropping.

  2. Paul

    style=”width: 141px; height=176px; overflow=hidden” IS WRONG

    style=”width: 141px; height:176px; overflow:hidden;” IS RIGHT

  3. Derp

    To crop to a specific position, can’t you do:

    div style=”width: 100px; height: 100px; overflow: hidden;”

    div style=”margin-left:-50px;”

    img src=”whatever.png”/



  4. Gavin Hudson

    @Derp: Nope. At least, that doesn’t work for me, but I’d love to have a way of doing it.

  5. Pingback: RE: Image cropper using icefaces1.8 - Forums -

Leave a Reply

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