Hasan Setiawan

Write, write, write give your wings on code!

Follow me on GitHub

CSS perfect full page background image

The goal here is a background image on a website that covers the entire browser window at all times. Let's put some specifics on it:

  1. Fills entire page with image, no white space
  2. Scales image as needed
  3. Retains image proportions (aspect ratio)
  4. Image is centered on page
  5. Does not cause scrollbars
  6. As cross-browser compatible as possible
  7. Isn't some fancy shenanigans like Flash

      
        // html


        // css
        #bg {
          position: fixed;
          top: -50%;
          left: -50%;
          width: 200%;
          height: 200%;
        }
        #bg img {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          margin: auto;
          min-width: 50%;
          min-height: 50%;
        }