Background image that fills entire viewport

If you want to have image in page background that will fill entire viewport, no matter what screen orientation, aspect ratio or dimensions are, then using CSS3 background-size: 100% or background-size: cover won’t help you.

In fact, to solve this problem, you can’t use pure CSS and you must help yourself with a block element.

The fastest solution

Solution, that comes, when you ask Google about background image that fills entire screen is usually something like this:

    background: url('cranes.gif') no-repeat left top fixed; 
    background-size: cover;

(of course, image must be large enough to avoid ugly pixels on large screens)

However, this will work fine only on landscape-oriented devices like monitors or TVs. If you have a mobile device (portrait mode) or pivot your screen you’ll see ab ugly-looking effect with empty half of the screen.

A bit fancy one

If filling entire viewport is far more important than image look, aspects or dimensions (i.e. useful for very simple langing pages with large enough background image) then you should help yourself with properly styled block element:

    <div id="background">
        <img src="mena.jpg" alt="" />

And style it like that:

    width: 100%; 
    height: 100%; 
    position: fixed; 
    left: 0px; 
    top: 0px; 
    z-index: -1;

#background img
    width: 100%;
    height: 100%;

Once again. We have one image (landscape or portrait) that we’re trying to fit to two different screen orientations. Even with big enough background image, that hasn’t got many details, on one of these orientations it will look blury / ugly / pixelized. Keep it in mind — this is solution for only certain situations.


This post is based on this slightly modified Stack Overflow answer.

Leave a Reply