开发者

What is the best way to crop an image with CSS?

开发者 https://www.devze.com 2023-01-19 12:33 出处:网络
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

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.


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;
}


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">
0

精彩评论

暂无评论...
验证码 换一张
取 消