tags:

views:

54

answers:

2

I want to show a photo in my page, the DIV layer is 500 * 500px. I will replace the picture very often , the picture size is not sure, may be horizontal version may be vertical version, maybe 800*600px maybe 576*720px. I don't want to get the photo deformation. How to set CSS or JS, make the photo show only the center 500 * 500 px, hide the around part. Thanks.

+5  A: 

Use a background image on a DIV with pre-defined dimensions, and set the image position to 50%, which essentially centers it. Whatever overflows the 500x500 will be cropped...

#yourImageDiv {
  background: url(../img/image.jpg) no-repeat 50%;
  height: 500px;
  width: 500px;
}
Josh Stodola
+2  A: 

One nice trick is to use a transparent PNG instead of a div and apply a background-image style to it. That way you get to use the image as you normally would (inline, etc.) but can crop at will.

#cropper {
  width: 500px;
  height: 500px;
  background-image: url(myBackgroundImage.png);
  background-repeat: no-repeat;
  background-position: center center;
}

...

<img id="cropper" src="clear.png">
Robusto
Very nice! This can have an `alt` tag as well.
Pekka
@Pekka: Exactly.
Robusto