Skip to Content

Gareth53.co.uk - the online home of Gareth Senior

CSS Background Images Applied to the HTML element

5:24p.m., Thu 7 Jan 2010

You can apply background images to the HTML element. I'd never actually done it until today, or even considered doing it. But it's been a handy solution to an unusual problem.

The Problem (some background info)

The new Heart FM site (due to launch at the end of January 2010 if you're loking before that) has a fixed width, center-aligned design.

The dimensions of the grid are dictated by both ad formats and the dimensions of legacy images. As a result the design process threw up a site with an actual full width of 1008 pixels.

Here's a screengrab (click for the full-size image)

The site design - too wide!

However a significant proportion of our users are using an OS with the screen dimension set to 1024x768 (around 30%).

Given the scrollbars on a browser can be up to 16 pixels wide, we've got a design that could generate an annoying smidge of horizontal scrolling.

In the early stages of development we got around this by generating the left and right edges of the site with a center-aligned background image applied to the body of the document. Users with smaller screen resolutions simple wouldn't see the background image - which is fine because their browser window is a fine enough visual 'edge'.

A later iteration to the design saw a new ad format incorporated and a requirement for more imagery spanning that full 1010 pixels - a vertical gradient behind the main ad at the top of the page.

Here's a screengrab (click for the full-size image)

The site design - too wide!

The Solution

You can apply a background image to both the html tag and the body element - imagery that will be cropped when the browser width is narrower than the image without horizontal scrolling.

The background attached to the html element is a gradient, the background attached to the body is the left and right edges of the frame. The gap between those edges is transparent, allowing the gradient to show through. The gradient is handful of pixels narrower than the gradient.

Example CSS declarations html {
    background:#fff url(../img/bg-leaderboard.png) no-repeat top center; }
 
body {
    background:transparent url(../img/bg-body.gif) repeat-y top center;
}

When I first tried this out I expected it to work some browsers but not all. But curse my pessimism, it worked fine!

Tested and verified in:

Win XP
Internet Explorer 6/7/8, Firefox 2, 3, Opera 8/9, Google Chrome 1.0

OSX
Safari 3, Opera 10, Firefox 3, Chrome 1.0

I'm not the first to do this BTW, I'm sure there's millions of others and there's bound to be some gotchas further down the line, I can imagine, for example, potential problems when the rendered document isn't as deep as the browser viewport, and there'll be others ...

Some Relevant Links

Latest Posts

Blog Categories