Emulating Fixed Positioning

From CSS Discuss

Jump to: navigation, search

(See also Ghost In The Box and Frames without Frames.

If you want to position anything relative to the window instead of relative to the document or the default position in the document flow, you can use a mechanism that CSS provides you, called Fixed Positioning. That type of positioning is widely supported:

  • IE for Macintosh,
  • Mo Zilla and other browsers based on Gecko such as Netscape6+,
  • Safari/Konqueror
  • Opera

IE for Windows doesn't, however, and that is the big reason you very seldom see pages using fixed positioning on the net. Here follows a method of emulating fixed positioning in IE for Windows.

The underlying theory

The Root Element 's container is the viewport and if you force it to a height of 100% and disable scrolling you get a non-scrolling root element the same size as the window (the viewport). An absolutely positioned element in the document will be positioned relative to the closest positioned ancestor, or the root element if no such ancestor exists.

Thus, we can easily get something that is equivalent to fixed positioning using mere Absolute Positioning. But as we removed the scrolling of the root element, what do we do if the window is smaller than the content? The answer is that we put the scrolling on the body element instead. But, this destroys the use of scroll wheels or arrow keys for scrolling in browsers other than IE for Windows. Well, those browsers support fixed positioning anyway, so we only need to hide the styles that emulates that behavior from them but not for IE for Windows. This is easily done through the Star Html Hack .

An example stylesheet

/* For fixed positioning savvy browsers */
.fixed{
    position: fixed;
}

#header{
    top: 0;
    left: 0;
    height: 80px;
}

#footer{
    bottom: 0;
    left: 0;
    height: 30px;
}

body{
    padding: 80px 0 30px;
}

/* For IE for Windows \*/
* html{
    width: 100%;
    height: 100%;
    overflow: hidden;
}

* html body{
    width: 100%;
    height: 100%;
    overflow: auto;
}

* html .fixed{
    position: absolute;
}
/* */

IE history bug triggered by the emulation

As detailed in Ghost In The Box , Eric Bednarz has a nice page summarising this workaround.

Eric's demo exhibits the IE history bug triggered by this code. If you click the "Jump over all" link, you'll find that your browser "Back" button subsequently fails to return you from the anchor to your previous location on the page. I have no idea why this happens or how to fix it.

The position: fixed implementation in Firefox does not suffer from this limitation.

Personal tools