Search code examples
htmlimagecssbackground-position

How to center an image horizontally while pushing the bottom (unknown resolution) and keep centered if window is too narrow


Let's say I have an image of unknown resolution. I want to center it horizontally, even if the window is narrower than the picture, and push the bottom of the window to fit the height of this picture.

How can I achieve that with css only? (no javascript)

Obviously the picture will be in an < img > tag since this is the only way to push the bottom. Align it center is easy, the hard part is to keep it centered just like a background-position:center top because when simply centering this < img > tag it will hit the left border of the window instead of overflowing hidden and staying centered.

Thanks!


Solution

  • Voila: https://jsfiddle.net/gwja6f6z/

    HTML:

    <div id=main>
        <div id=imgwrp>
            <img src="https://upload.wikimedia.org/wikipedia/commons/9/94/Ingres%2C_Self-portrait.jpg" border=0>
        </div>
    </div>
    
    <p>
    The picture stays center and does not hit the borders of the window when window is too narrow, and this text is pushed without knowning the height of the picture.
    </p>
    

    CSS:

    html, body {
      width:100%;
      height:100%;
      text-align:center;
      overflow-x:hidden;
    }
    
    #main {
      position:relative;
      left:50%; /* This div is just a 0px width line in middle of window  */
      width:0;
      overflow-x:visible;
      text-align:center;
    }
    
    #imgwrp {
      display:inline-block; /* Image container width is same as image itself */
      position:relative;
      margin:0 auto 0 auto;
    }
    
    #imgwrp img {
      display:block;
      position:relative;
      margin-left:-50%; /* The image is pushed left by 50% its container width */
    }