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

I want to show a photo on my page, the DIV layer is 500 * 500 pixels. I often replace the picture, the image size is not sure, maybe the horizontal version can be vertical, maybe 800 * 600 pixels, maybe 576 * 720 pixels.

I do not want to get warped photos. How to install CSS or JS, make the photo show only the center 500 * 500 px, hide part around it.

+4
source share
2 answers

Use a background image on a DIV with predefined sizes and set the image position to 50%, which essentially centers it. Regardless of the overflow, 500x500 will be cropped ...

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

One nice trick is to use a transparent PNG instead of a div and apply a background image style to it. This way you can use the image as usual (embedded, etc.), but you can crop as desired.

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

...

 <img id="cropper" src="clear.png"> 
+3
source

All Articles