Fit, scale and center image responsively to browser window (CSS)

前端 未结 1 1755
遇见更好的自我
遇见更好的自我 2021-01-06 01:44

How do I have an image, irrespective of portrait or landscape:

  • centered responsively both horizontally and vertically (remains centered as browser window is r
相关标签:
1条回答
  • 2021-01-06 02:26

    Here's a solution that satisfies all of the above with only basic CSS (no CSS3 required):

    http://jsfiddle.net/dvidby0/sytj1uws/1/

    HTML

    <div class="container">
    <!-- this is a landscape image-->
    <img src="http://upload.wikimedia.org/wikipedia/commons/1/15/Cat_August_2010-4.jpg"/>
    <!--or use this portrait image; still works
    <img src="http://upload.wikimedia.org/wikipedia/commons/9/9d/Britishblue.jpg"/>
    -->
    

    CSS

    .container {
    width: 80%;
    height: 80%;
    position: absolute;    
    margin:auto;
    top:0;
    bottom:0;
    left:0;
    right:0;
    background-color: #aaa;
    }
    
    img {
    max-width: 100%;
    max-height: 100%;  
    position: absolute;
    margin:auto;
    top:0;
    bottom:0;
    left:0;
    right:0;
    }
    
    0 讨论(0)
提交回复
热议问题