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.