CSS: fluid layouts and column background

Fluid layouts with CSS should be used whenever it's possible, because they actually add an extra level of flexibility and scalability to our pages that it's frankly impossible to reproduce with other techniques. However, if we want to get the effect of a background color that follows the height of a column entirely, using fluid layouts poses some problems. First and foremost, we have to use a background image for the column. Suppose that we want to apply this effect to the right column of a basic two-column template with header and footer. What we have to do is to create a background image that will have an overall width much, much greater than normal. In this example, we'll create a background image that is 2000 pixels wide and 20 pixels tall (height is not relevant in this case).

Second, we set the width of the right column to the 25% of the total parent's width. So our background image will be transparent for the 75% of its width and with a solid color for the remaining 25% which, in this case, is 500 pixels (the 25% of 2000 is 500). Now that we've done some maths, we can draw our HTML structure:

<div id="site">


    <div id="branding"><h1>Site Name</h1></div>
    
    <div id="content">
    
        <div id="main">
        
            <p>...</p>        
        </div>
        
        <div id="content-sub">
         <p>...</p>
        </div>
    
    
    </div>
    
    <div id="site-info">Site Info</div>
</div>

Our first styles are really simple. They are only a standard implementation of a two-column layout with floats:

body {
    margin: 0;
    padding: 2em 0;
    font: 100% Arial, sans-serif;
    background: #ccc;
}

#site {
 width: 70%;
 margin: 0 auto;
 background: #fff;
 color: #333;
}

#branding {
 padding: 3em;
 text-align: center;
 background: #000;
 color: #fff;
}

#branding h1 {margin: 0;}

#main {
 float: left;
 width: 75%;
}

#content-sub {
 float: right;
 width: 25%;
}

p {padding: 0 1em; line-height: 1.4;}

#site-info {
 padding: 3em;
 font-weight: bold;
 text-align: center;
 color: #fff;
 background: #000;
 clear: both;
}

Instead, the interesting part happens when we stylize our content element:

#content {
 height: 100%;
 overflow: hidden;
 background: url(bg-col.gif) repeat-y 75% 0;
}

Since our column is the 25% of the total, to get the horizontal offset of the background image we have to subtract 25 from 100 and we get 75 that we'll later use with the background-position property. Further, to make the background image repeat vertically, we specify repeat-y on the background-repeat property. You can see a demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.