Emulating position: fixed; in IE 6 & below

A little background:

#bar { width: 100px; height: 100px; background:red; z-index: 100; }

* html #bar { /*\*/position: absolute; top: expression((176 + (ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop)) + ‘px’); right: expression((20 + (ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft)) + ‘px’);/**/ }

#foo > #bar { position: fixed; top: 176px; right: 20px; }

Internet Explorer 6 and below do not understand the CSS property and value position: fixed;. All the better browsers (IE7, Firefox/Mozilla, Safari, Opera) understand and apply this rule.

If you are unfamiliar with position: fixed; it basically makes an element stay in the same position on a page while the page is scrolled. When using position: fixed; you should set the position using a combination of top or bottom and left or right.

digg_url = ‘http://digg.com/programming/Emulating_position_fixed_in_IE_6_below’;

The CSS (with a splash of JavaScript):


#bar { width: 100px; height: 100px; background: red; z-index: 100; }

* html #bar { /*\*/position: absolute; top: expression((176 + (ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop)) + 'px'); right: expression((20 + (ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft)) + 'px');/**/ }

#foo > #bar { position: fixed; top: 176px; right: 20px; }

How it works:

1) The first line of CSS is the generic rules that apply to all browsers, in this case width, height, background and z-index.

2) The second line of the CSS is being applied only to IE6 and below by use of the * html filter/hack and it is being hidden from Mac/IE using the Tan Hack (/*\*/…/**/). A JavaScript expression is being used to determine where to place the element that needs to have a fixed position. You don’t need to change the expression at all other than making sure your numbers all match up (the highlighted areas).

3) The last line is for all the better browsers that already know how to handle position: fixed;. These rules are not applied to IE6 and below because we are using the child selector (#foo > #bar), which IE6 and below does not understand.

The most important things about this little fix are making sure your numbers (the highlighted numbers above) match up. If they don’t, your element will likely be in different positions in IE6 and below and all the better browsers.

This technique was found by Matt Siegler.
This technique was adopted from http://www.howtocreate.co.uk/fixedPosition.html.
This technique was adapted by Chip Adams.

You can see this example by looking at the box to the right.

This is a box positioned smoothly to the right in all browsers.

Leave a comment