Resize and crop image with CSS

前端 未结 6 1958
有刺的猬
有刺的猬 2021-01-12 13:37

I\'d like to resize and crop an image of unknown dimensions, just with css. The image should be resized/cropped to completely fill a container of known dimensions, cutting o

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-12 14:12

    You could use clip() an old CSS rule http://tympanus.net/codrops/2013/01/16/understanding-the-css-clip-property/ , but it is easy for known image size .

    For unknown image size, but known container size, you can use line-height: /* height of container */; and text-align:center; to basicly center a single inline element in this container.

    The single image then can be set with : vertical-align:middle; and negative margin to virtually reduce its size , lets say : margin:-50%;.

    For image too big in first place, use min or max width height to reduce their size.

    .container {
        width: 180px;
        height: 160px;
        overflow: hidden;
        border:red solid 2px
    }
    .container {
        line-height:160px;
        text-align:center;
    }
    .container img {
        vertical-align:middle;
        margin: -50%;
        min-width:100%;
        max-height:150%;
    }
    

    DEMO : http://jsfiddle.net/q9jFx/27/

    a few other demo if this makes you curious : http://codepen.io/gcyrillus/pen/etxky , http://codepen.io/gcyrillus/pen/BdtEj , http://codepen.io/gcyrillus/pen/hyAmd (3 different test of zooming/cropping img) , within a basic slider http://codepen.io/gc-nomade/pen/Hdpku , test imgvs bg http://codepen.io/gcyrillus/pen/wsjBJ

提交回复
热议问题