How to set an image's width and height without stretching it?

前端 未结 12 1612
南旧
南旧 2020-11-28 05:22

If I have:

#logo {
    width: 400px;
    height: 200px;
}

then


12条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 05:54

    Load the image as a background for a div.

    Instead of:

    
    

    do

    
    

    All browsers will crop the part of the image that doesn't fit.
    This has several advantages over wrapping it an element whose overflow is hidden:

    1. No extra markup. The div simply replaces the img.
    2. Easily center or set the image to another offset. eg. url(pic) center top;
    3. Repeat the image when small enough. (OK, dunno why you would want that)
    4. Set a bg color in the same statement, easily apply the same image to multiple elements, and everything that applies to bg images.

    Update: This answer is from before object-fit; you should now probably use object-fit/object-position.

    It is still useful for older browsers, for extra properties (such as background-repeat), and for edge cases (For example, workaround Chrome bugs with flexbox and object-position and FF's (former?) issues with grid + autoheight + object-fit. Wrapper divs in grid / flexbox often give... unintuitive results.)

提交回复
热议问题