How to emulate `position: fixed` using absolute positioning
html {
position: absolute;
height: 100%;
overflow: hidden;
}
body {
height: 100%;
overflow: auto;
}
.fixed {
position: absolute;
}
Look here for a demo of it working.
There are a couple of big advantages to emulating position: fixed
.
- Better compatibly with older browsers.
- Fix an element relative to any container you like, not just the document window.
Written by Gavin McFarland
Related protips
5 Responses
Interesting...
If you do this, will it change the behavior of the whole page? You're essentially scrolling the body and your "fixed" element is staying still.
Considering how touchy CSS is in different browsers, this seems like it could cause problems for you later on. Have you had it cause any issues?
You raise some good concerns. I've tested it in general use across most browsers both old and new and I haven't experienced any abnormal behaviour. However I'd like to see how it fairs with more complicated sites.
There is an interesting article that talks about some quirks that occur older versions of Opera (and IE5 eurgh), like the mouse wheel not working, but I should think these issues aren't applicable to modern practices.
What I'm most concerned about is how this works on mobile devices. Quick tests show that it's a bit buggy. On iOS the scrolling is juddery and the fixed position is intermittent. Remy Sharp talks about some of the issues with position fixed and scrolling in iOS that are worth reading also.
May go together well with a tip I wrote a while back: https://coderwall.com/p/4_dt8w
I used the html and body part that you use for this, in Marvel's site (marvel.la).
That fixes the way browsers calculate their width (some calultates counting the scrollbar inside, and some outside). Weird, but total nightmare in a responsive site where you have breakpoints, since these fires at 'different sizes' when using javascript.
This fix arise some troubles, like Webkit doesn't animate no more. And calculates the offset to the top of the document different thant the rest of the browsers. Really pain in the ass.
So i'll asume that your css for fixing position would suffer such problems.
Cheers
@rockinggabi interesting. Do you have an example of how Webkit fails when it tries to animate?