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

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

    Try putting your image into a container like so:

    HTML:

    CSS:

    div
    {
        width: 200px;
        height: 200px;
        overflow: hidden;
    }
    
    div > img
    {
        width: 300px;
    }
    

    Here's a fiddle.

提交回复
热议问题