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

后端 未结 14 1066
再見小時候
再見小時候 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:42

    Here is a simple CSS only solution (JSFiddle), works everywhere, mobile and IE included:

    CSS 2.0:

    html, body {
        height: 100%;
        margin: 0;
        padding: 0;
    }
    
    img {
        padding: 0;
        display: block;
        margin: 0 auto;
        max-height: 100%;
        max-width: 100%;
    }
    

    HTML:

    <body>
      <img src="images/your-image.png" />
    </body>
    
    0 讨论(0)
  • 2020-11-28 19:42

    If you are willing to put a container element around your image, a pure CSS solution is simple. You see, 99% height has no meaning when the parent element will extend vertically to contain its children. The parent needs to have a fixed height, say... the height of the viewport.

    HTML

    <!-- use a tall image to illustrate the problem -->
    <div class='fill-screen'>
        <img class='make-it-fit' 
             src='https://upload.wikimedia.org/wikipedia/commons/f/f2/Leaning_Tower_of_Pisa.jpg'>
    </div>
    

    CSS

    div.fill-screen {
        position: fixed;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        text-align: center;
    }
    
    img.make-it-fit {
        max-width: 99%;
        max-height: 99%;
    }
    

    Play with the fiddle.

    0 讨论(0)
提交回复
热议问题