How to Fix Randomly Disappearing Absolutely-Positioned Elements in IE
After 8 years, you’d have thought all IE6’s bugs would be well-documented and understood. Actually, after that time, you’d have hoped most of the issues would have been fixed in IE7 or IE8!
I was recently contacted by a frustrated developer who’d experienced disappearing absolutely-positioned elements in IE. The bug is quite bizarre, it’s not often you experience it, and there’s little information about it on the web. Hopefully, this article will go some way to rectifying that situation.
Consider this layout:
The HTML elements are coded in the order specified, i.e. content blocks 1 and 2, header 3, right-hand block 4, and footer 5. The outer container is set to position: relative and all items have widths assigned so IE hasLayout. It may not be the most efficient layout but it’s valid and works in all browsers. Except IE6, IE7, and possibly IE8 … sometimes.
The first time you visit the page, IE can refuse to show the header. However, the header may re-appear when visiting a similarly-coded page on the same site. It can also re-appear when you return to the first page?
The problem is caused by an IE bug that hides an absolutely-positioned element when it’s coded immediately before or after a floated element (it’s next to a floated sibling). Unfortunately, this condition does not necessarily trigger the bug — it’s time dependent! The timing of the file downloads and the rendering speed affect whether it occurs or not. In my experience, the bug seemed less likely to occur if some files were cached.
So, here’s an example page.
Unfortunately, the bug is so inconsistent that it’s impossible to create one that’s guaranteed to work (or fail?)
On my local PC’s server, the header disappears in IE6, 7 and 8. On the SitePoint server, it only disappears in IE6 and 7. You may have a different experience.
In addition, fake IEs such as IETester do not necessarily exhibit the same problem. I’d recommend using a real version of IE such as one within a VM (see Run IE6, IE7, and IE8 on the Same Machine Using Windows 7 XP Mode or How to Run IE6, IE7 and IE8 on Windows 7 HOME).
Fortunately, there is a quick and dirty solution: simply place an empty un-positioned static <div></div> immediately before and/or after the absolutely-positioned element. In the fixed example, an empty <div></div> after the header prevents the problem occurring.
Semantic HTML devotees will be horrified but I’m afraid there doesn’t appear to be a CSS-only fix … unless anyone knows otherwise?
A better solution would be a more efficient layout without the absolutely-positioned header. Unfortunately, that can require a significant amount of code re-factoring if you haven’t tested IE early and often.
Have you experienced this strange bug before? Or have you given up on IE altogether?