HTML and CSS

Fixed Positioning

Fixed positioning is a brilliant piece of CSS. Now you know that if I'm starting off a section like that, I'm giving you the good news first to soften the blow. Because as brilliant as fixed positioning is, it's not supported in Internet Explorer and, as such, can be used only for Mozilla, Opera, Safari, and other browsers that do support it. Phooey!

Fixed positioning enables you to fix a box anywhere on the page. Unlike absolute positioning, fixed elements are positioned in relation to the viewport (you knew that just had to be somewhere in this tutorial). Look at Example 12-6.

Example 12-6. Fixed positioning
<style type="text/css">
#nav {
           position: fixed;
           left: 0px;
           top: 0px;
           background: #ccc;
           width: 100%;
           }
ul, li, a {
           list-style-type: none;
           display: inline;
           text-decoration: none;
           padding-left: 3px;
           padding-right: 3px;
           }
</style>

So check out what I just did. By positioning the nav div to 0 left and 0 top, adding a gray background, and setting my width to 100%, I oh-so-cleverly made my navigation look pretty darned close to a standard menu, just as you'd find in the browser itself (see Figure 12-9).

Figure 12-9. A fixed-position navigation bar.

NOTE

Although IE 6.0 doesn't support the fixed scheme, it doesn't entirely disallow you from using it. You'll get the positioned box, but it will scroll off along with the rest of the content instead of remaining fixed in place.


In browsers that support fixed positioning, this menu will remain fixed no matter what else moves. So, if I scroll the content, it will disappear under the menu (see Figure 12-10).

Figure 12-10. The content scrolls beneath the fixed-position nav.

You can see why I'm frustrated by IE's lack of support for fixed positioningwhat a useful positioning scheme.

NOTE

Static positioning is the fourth positioning type. It simply positions a box in the normal flow and, because of that, is rarely used. You can think of using static positioning as similar to using the text-align: left; property and value. It's the default behavior, so it is used only to override an earlier rule. You'll rarely see static position in use as a result.