share...

© Mat Hayward 2010
19 April 10

Position Fixed Tutorial

If you’ve read my Position Fixed Showcase blog post, you’ll know that I’ve noticed a recent trend for fixed position elements and background image in website design. Here’s a tutorial on how to achieve this effect yourself.

Fixed Background

This is the easiest fixed position effect to achieve.

1. We’ll start by building a basic webpage in XHTML and CSS. The webpage has a floated two div layout (navigation and content).

XHTML

<div id="nav">
   <ul>
      <li><a href="#">Home</a><li>
      <li><a href="#">Link 1</a><li>
      <li><a href="#">Link 2</a><li>
   </ul>
</div>
<div id="content">
   <p>A lot of content that would cause the page to scroll…</p>
</div>

CSS

body {
   background: url("bg.jpg") no-repeat;
}

#nav {
   background: #FFFFFF;
   width: 300px;
   margin: 10px 0px 0px 10px;
   float: left;
}
       
#content {
   background: #FFFFFF;
   width: 450px;
   float: left;
   padding: 10px 10px 10px 10px;
   margin: 10px 0px 10px 20px;
}

This will give us something like this:

Position Fixed Screenshot 1

But you’ll notice that, when you scroll through the content, the background image ends, leaving a lovely white space!

Position Fixed Tutorial Screenshot

2. So the solution? Fix the position of background image. And this is really simple. Simpy change the line of CSS that adds the background image to the body.

CSS

body {
   background: url("bg.jpg") no-repeat fixed;
}

Now, as you scroll through the content, the background image does not move!

Position Fixed Tutorial Screenshot

View a demo

Fixed Elements

Unfortunately, at the moment, when scrolling through the content, the navigation disappears, and to use it, you’ll have to scroll all the way back up. So let’s fix it to the browser window.

1. Using what you already have from before, add “position: fixed” to the navigation and position it at the top left of the browser window.

CSS

#nav {
   background: #FFFFFF;
   width: 300px;
   margin: 10px 0px 0px 10px;
   float: left;
   position: fixed;
   top: 0px;
   left: 0px;
}
Position Fixed Tutorial Screenshot

2. Oops! The nav is definitely fixed to the top left of the browser window, but it’s also obscuring the content!

No problem, add some left margin to the content and you’re sorted.

CSS

#content {
   background: #FFFFFF;
   width: 450px;
   float: left;
   padding: 10px 10px 10px 10px;
   margin: 10px 0px 10px 320px;
}
Position Fixed Tutorial Screenshot

View a demo