max-height AND max-width with CSS only

前端 未结 6 1401
无人共我
无人共我 2021-02-02 07:43

First post for me here.

I\'m using a div to crop thumbnail images all in the same proportions (180wx170h). I\'m getting stuck when dealing with portrait as well as land

6条回答
  •  清歌不尽
    2021-02-02 08:21

    Edit: I have improved the solution, see here: https://stackoverflow.com/a/34774905/1663572


    I'm using this solution, which i found, when I was trying to fit and center images into squares (or whatever). It is brilliant in combination, where you set padding-bottom and height 0 to its container - that makes it responsive with fixed ratio.

    Works in IE9 and higher. For IE8 and below some CSS hacks needed.

    HTML

    .container {
        height: 0;
        padding-bottom: 100%; /* Or 75% for 4:3 aspect ratio */
        position: relative;
        overflow: hidden;
    }
    .container img {
        display: inline-block;
        max-width: 90%; /* You can use different numbers for max-width and max-height! */
        max-height: 75%;
        width: auto;
        height: auto;
    
        position: absolute;
        left: 50%; /* This sets left top corner of the image to the center of the block... */
        top: 50%; /* This can be set also to bottom: 0; for aligning image to bottom line. Only translateX is used then. */
        -webkit-transform: translate(-50%,-50%); /* ...and this moves the image 50 % of its width and height back. */
        -ms-transform: translate(-50%,-50%);
        -o-transform: translate(-50%,-50%);
        transform: translate(-50%,-50%);
    }
    
    /* Fallback for IE8 */
    @media all\0 { 
        .container img {
            margin: auto;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
        }
    }
    

    Try it here: http://jsfiddle.net/thiemeljiri/uhdm4fce/4/

    Notice: If using bootstrap change the class .container to something else.

提交回复
热议问题