Creating A Full Width Background Using CSS

The Problem - Cropped Background Upon Scrolling

Here's the problem: create a block-level (full page width) element and set either a repeat-x background image or background colour, only to see that background cropped to the width of the browser viewport when performing a horizontal page scroll.

This problem occurs when using a fixed-width block-level element (such as content containers) with other block-level elements (such as headers, menu-bars or footers) that run through the full width of the page. If the page is then viewed with a browser window sized less than the width of the container, then scrolling the container into view displays a cropped header, menu and/or footer.

The following screen-shot shows the problem when viewed in Firefox.

And here's the code used to create the above result.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <style title="text/css">
* {
    margin: 0;
    padding: 0;
    border: 0;
}
#menu {
    height: 50px;
    background: #0a0;
}
#container {
    height: 50px;
    width: 500px;
    background: #a00;
}
    </style>
</head>
<body>
    <div id="menu">
This is the menu.
    </div>

    <div id="container">
This is the container.
    </div>
</body>
</html>

The Solution - min-width

I've fallen foul of this problem before and seen it occur on plenty of other sites. One way to prevent the cropping problem above is to set a min-width CSS attribute on the element containing the full width background. Amending the #menu id selector in the above code solves the problem:

#menu {
    min-width: 500px; // set to the width of the #container
    height: 50px;
    background: #0a0;
}

I've found that applying the min-width attribute to the body also ensures the backgrounds of all non-width-constrained block-level elements extend to the full width of the page, rather than just the non-scrolled viewport.

This seems to apply to all the browsers that I've checked so far, so it's likely W3C stardard-compliant behaviour, but it does seem somewhat unintuitive.

Labels: ,

Bookmark and Share
Subscribe to this blog
rss news feed icon