Horizontal background extending on fixed width sites

Often when building a fixed width website, there are blocks of content whose backgrounds should extend horizontally beyond the fixed width area. Footers are a good example of this, but there are other cases as well.

There are a few ways to go about achieving this: wrapper divs, a mess of absolute and relatively positioned elements… or there’s a nice little CSS hack using the :before pseudoclass.

#myblock    /* Main content block */
{
    width: 940px;
    margin: 0 auto;
    background: steelblue;
    height: 200px;
}

#myblock:before    /* The pseudoclass hack */
{
    position: absolute;
    width: 100%;
    left: 0;
    background: steelblue;
    height: 200px;
}

A few things to note:

  • The block must have a fixed height, otherwise the :before extensions won’t match the main content height.
  • The content block must not be position relative, otherwise the absolute positioning of the :before pseudoclass won’t work properly.
  • This works in IE8+, Firefox, Chrome, Safari… IE7 and lower have no support for the CSS :before pseudoclass.
  • This is best suited for solid colours. A tiling image should be okay too. A background image at a specific location in the content block will probably incur z-index problems.
    For most browsers, this can be fixed by setting the :before pseudoclass to have a z-index of -1, but this will not work in IE8. There doesn’t appear to be a solution for this problem.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s