How to resize an image to fit in the browser window?

后端 未结 14 1221
再見小時候
再見小時候 2020-11-28 19:00

This seems trivial but after all the research and coding I can\'t get it to work. Conditions are:

  1. The browser window size is unknown. So please don\'t propose
14条回答
  •  无人及你
    2020-11-28 19:34

    Resize Image to Fit the Screen by the Longest Side maintaining its Aspect Ratio

    img[src$="#fit"] {
        width: 100vw;
        height: auto;
        max-width: none;
        max-height: 100vh;
        object-fit: contain;
    }
    
    • width: 100vw - image width will be 100% of view port

    • height: auto - image height will be scaled proportionally

    • max-height: 100vw - if image height would become more than view port it will be decreased to fit the screen, consequently image width will be decreased because of the following property

    • object-fit: contain - the replaced content is scaled to maintain its aspect ratio while fitting within the element's content box

      Note: object-fit is fully supported only since IE 16.0

提交回复
热议问题