Tuesday, 30 June 2015

Fullscreen background image with CSS

Finding a way to include a fullscreen background image to a webpage wasn’t as easy as I imagined. The web is littered with different approaches, with varying mileage. The approach I originally chose looked fine on my laptop, and even the device emulation in Google Chrome led me to believe I had a fullscreen background on all possible different devices. However, when I looked at the page with my iPad it looked horrific. So, back to the drawing board…

Fortunately I found a solution on Stack Overflow.

For a uniform result, apparently the fixed background needs to be attached to the html element:

html {
    background: url(theBackgroundImage.jpg) no-repeat center center fixed;
    background-size: cover;
    height: 100%;
    overflow: hidden;
}

The scrolling should then be set to the body element:

body {
    height: 100%;
    overflow: scroll;
}

Good, that works. However, now the 1.890 × 1.280 pixel image fit for a high-resolution screen is also fed to a tiny smartphone display. The CSS3 standard gives us the possibility of performing Media Queries. With these queries we can figure out a number of characteristics of the client, such as width, height and orientation. Based on these characteristics different CSS styling is applied to, for instance, different widths.

The following CSS snippet is only applied to devices with a width of less than 767 px, such as smartphones. This enables us to create a smaller version of the background image and feed it to devices with a smaller screen size.

@media (max-width: 767px) {
html {
    background: url(theBackgroundImage_768max.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    height: 100%;
    overflow: hidden;
}
}

References

http://stackoverflow.com/questions/23299960/prevent-fixed-position-background-image-cover-from-resizing-in-mobile-browsers

Share Your Thoughts