Creating Fixed Headers with CSS



This well thought out, easy to understand CSS3 video tutorial will show you how to create a fixed header with CSS.

The goal here is to make a header that stays fixed to the top of the screen, whether you are scrolling or not. It’s a great option to have in your coding arsenal for clients who want to have a website that features fast and easy access to navigation, or perhaps just want to draw attention to a promotion with an eye-catching banner ad. Either way, this lesson will show you how to set up both a full-width header and one that matches up with custom width pages.

He begins with a basic web page that has a set width and a small header that matches the width set up at the top of the page. so we just need to make that header follow us as we scroll down the page. Here is what the code looks like in the beginning.

<head>
<style type="text/css">
body{
    margin:0px;
    background:#000;
}
.header {
    height:50px;
    background:#F0F0F0;
    border:1px solid #CCC;
    width:960px;
    margin:0px auto;
}
.content {
    width:960px;
    background: #F0F0F0;
    border: 1px solid #CCC;
    height: 2000px;
    margin: 20px auto;
}
</style>
</head>
<body>

    <div></div>

    <div></div>

Start by changing the header position to fixed; and the width to 100%;. After this the content margin is set to 70px auto;, which adds a total of 50pixels. This results in the header remaining at the to of the scree even when you scroll down, but it is not positioned at the top of the screen like many people would like. So adding the property top:0px; to the header will push that header to the top of the browser window.

Now if you prefer to have a header that matches the width of the content, then there is still a little work to get done here. Changing the header width to 960px; will create the proper size, but it still needs to be positioned correctly. To do this, we add a property of margin: 0px auto; to the header and then create a new class .header-cont { width:100%; position:fixed; top:0px; }. This then wraps the header division to apply the two classes to it. You can also now remove the top: and position: properties from the header.

<style type="text/css">
body{
    margin:0px;
    background:#000;
}
.header-cont {
    width:100%;
    position:fixed;
    top:0px;
}
.header {
    height:50px;
    background:#F0F0F0;
    border:1px solid #CCC;
    width:960px;
    margin:0px auto;
}
.content {
    width:960px;
    background: #F0F0F0;
    border: 1px solid #CCC;
    height: 2000px;
    margin: 70px auto;
}
</style>
</head>
<body>

<div class="header-cont">
    <div></div>
</div>

<div></div>

We hope you have enjoyed the tutorial and encourage you to send in requests for future tutorial topics. And before you hurry off, you may find this recent post on how to use Division, IDs and Classes to further organize your projects. Thanks for stopping by!