A search for meaning in software and life
RSS icon Email icon Home icon
  • Cropping an image in HTML

    Posted on August 4th, 2009 Peter No comments

    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">
    </div>
    

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

    Leave a reply