17 July 2009

position:fixed

Well well, I have learnt something new this morning. I think this new thing comes under the category of "how did I not already know this" but equally there is always the category of "kill IE6, please!".

I suspect that had IE6 dies off a good few years ago, I would already know this new technique as it is not supported in IE6. But I am very much of the opinion that we no longer need to support IE6 perfectly. I do not want to go into detail about browser support, I have spoken often enough about my thoughts on the matter.

So, onto the interesting part. Have you ever wanted to create a layout with an element which has a height of 100% minus some pixels? Or an equivalent for the width of an element? I know that I have on many occasions. Each time, I have had to either accept it cant be done or utilise some seemingly clever JavaScript to achieve my goal.

But, no more! position:fixed can now be our saviour. Picture the situation where you have a two column layout with your navigation in the left column and content in the right column. You want the left column to have a solid background colour and be 100% in height but leave a 50 pixel space at the top of the column. You might use the following markup:

<!DOCTYPE html>
<html>
<body>
 
<div id="LeftNavigation">
    <ul>
        ....a series of links
    </ul>
</div>
 
<div id="Content">
    ....some content
</div>
 
</body>
</html>


Now if you apply the following CSS:

#LeftNavigation {
    position:fixed;
    top:50px;
    bottom:0;
    background:#cccccc;
    overflow:scroll;
}
#Content {
    margin-left:310px;
}


You should see things exactly as I described above. The key styles are on the LeftNavigation DIV, the position, top and bottom styles. You should be aware that this is not supported in IE6 but I have found it works in all the browsers I have tried.

If this is also new to you, have a little play - it has certainly brightened my day!

2 comments:

Den Odell said...

Good stuff! Liking your DOCTYPE there, too :)

James Norton said...

It's HTML5 baby! Like it or not, it seems to be the future.