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

后端 未结 9 1326
[愿得一人]
[愿得一人] 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 07:15

    object-fit property does the magic. On JsFiddle.

    CSS

    .image {
      width: 160px;
      height: 160px;
    }
    
    .object-fit_fill {
      object-fit: fill
    }
    
    .object-fit_contain {
      object-fit: contain
    }
    
    .object-fit_cover {
      object-fit: cover
    }
    
    .object-fit_none {
      object-fit: none
    }
    
    .object-fit_scale-down {
      object-fit: scale-down
    }
    

    HTML

    original image

    object-fit: fill

    object-fit: contain

    object-fit: cover

    object-fit: none

    object-fit: scale-down

    Result

提交回复
热议问题