How to center and crop an image to always appear in square shape with CSS?

后端 未结 9 1354
[愿得一人]
[愿得一人] 2020-12-02 06:19

I need to always crop a random-sized image to a square 160x160 using only CSS. The images should stay centered when cropped.

My markup should be:

<         


        
9条回答
  •  不知归路
    2020-12-02 06:56

    With the caveat of it not working in IE and some older mobile browsers, a simple object-fit: cover; is often the best option.

    .cropper {
      position: relative;
      width: 100px;
      height: 100px;
      overflow: hidden;
    }
    .cropper img {
      position: absolute;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    

    Without the object-fit: cover support, the image will be stretched oddly to fit the box so, if support for IE is needed, I'd recommend using one of the other answers' approach with -100% top, left, right and bottom values as a fallback.

    http://caniuse.com/#feat=object-fit

提交回复
热议问题