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
CSS
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:
But you’ll notice that, when you scroll through the content, the background image ends, leaving a lovely white space!
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
background: url("bg.jpg") no-repeat fixed;
}
Now, as you scroll through the content, the background image does not move!
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
background: #FFFFFF;
width: 300px;
margin: 10px 0px 0px 10px;
float: left;
position: fixed;
top: 0px;
left: 0px;
}
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
background: #FFFFFF;
width: 450px;
float: left;
padding: 10px 10px 10px 10px;
margin: 10px 0px 10px 320px;
}
- Event Photography
- Graphic Design
- Inspiration
- Showcases
- Travel Photography
- Tutorials
- Web Design
- Web Development
- Wedding Photography
- Wildlife Photography
- April 2010
- January 2010
- October 2009
- July 2009
- February 2009
- January 2009
- October 2008
- September 2008
- August 2008
- July 2008
- April 2008
