Saturday, December 27, 2008

Image Cropping with CSS

Part 1


Here is a quick, easy way to create a gallery by making all of your images squares. For simplicity's sake, in this example, all the images are 160x240px, both landscape and portrait. We'll make our squares 150px. In the HTML, wrap each image in a div, and give the div the following values:
div {
  width: 150px;
  height: 150px;
  overflow: hidden;
  float: left;
  margin: 0 10px 10px 0;
}

This sets up our square, and hides any part of the image that goes outside of that sqaure. Additionally, it adds a float and puts some space between each image.

Part 2


This gives us a good start to the gallery. My only compliant is that the images aren't centered within the div, we are only seeing the top left corner. So I wrote some jQuery that does this.
$(document).ready(function(){
  function centerImage(ele, w, h, pw, ph) {

      var heightdiff = -((h - ph) / 2);
      var widthdiff = -((w - pw) / 2);

      $(ele).css("margin-left", widthdiff);
      $(ele).css("margin-top", heightdiff);
  }

  $("div > img").load(function () {
      centerImage($(this), $(this).width(), $(this).height(), $(this).parent().width(), $(this).parent().height());
  });
});

See all this in action here.

From here, you can add more styles, link the images to a larger version, or anything else you can think of.

No comments: