Search code examples
cssimagefullscreen

Full screen image that scales


I am trying to create a home page that has an image that covers the entire screen, I followed a tutorial and got something like what I want, but it doesnt show the entire image.

I see a lot of sites that do this so it must be possible, I have an image that spans the entire screen but the image doesnt really scale to fit the browser, the bottom of the image is trimmed off.

html{               
            /* Ensure the html element always takes up the full height of the browser window */
            min-height:100%;    
            position:relative;          
        }

        body {
            background:url('bg.jpg') center center;
            background-repeat: no-repeat;
            background-attachment: fixed;
            background-size:cover;
            -webkit-background-size: cover;
            -moz-background-size: cover;
            -o-background-size: cover;

            /* Workaround for some mobile browsers */
            min-height:100%;

            font-family: 'Asap', sans-serif;    

        }

My image is bigger than the browser viewport but it doesnt get scaled so the whole image can fit, instead the bottom is chopped off.

HOw can I get it to scale with the browser? I am using bootstrap if there is anything there that can help.


Solution

  • There are several options. Choose which one suits you best.

    1. If you want the image to be all visible and to fill all of the background, use background-size:100vw 100vh or 100% 100%.
      Note: This will distort the image if it's not the same shape as the window.

          html {
            height:100%;
            background:#CCC url(http://lorempixel.com/g/500/500) center no-repeat;
            background-size:100vw 100vh;
          }

    2. To have your image fill the screen without distortion, you can use cover.
      Note: this will crop the image if it's not the same shape as the window.

          html {
            height:100%;
            background:#CCC url(http://lorempixel.com/g/500/500) center no-repeat;
            background-size:cover;
          }

    3. To have your image be the largest possible size without cropping or distorting, use contain.
      Note: this will not fill the whole window if the image is not the same shape.

          html {
            height:100%;
            background:#CCC url(http://lorempixel.com/g/500/500) center no-repeat;
            background-size:contain;
          }