IE Bug: Positioning, Containers, and HasLayout

I’m going to walk through a curious bug IE has had for quite some time relating to relatively positioned parents. Upon retrospect, this is a solved problem. Brunildo has two good examples. I wanted to work through the problem by myself, though, to make sure I understood its implications.

In short, this bug exists when one attempts to position an absolute element inside of a relative parent. This trick has existed a very long time. Simply make the parent relatively positioned, and the child will position itself absolutely to it, rather than the body (or any other parent with position relative).

With older versions of Internet Explorer, the child doesn’t act as expected. In the image below, I have three divs structured like so:

/* css */
#container {
	position: relative;
}
#main_col {
	margin-left: 100px;
}
#sub_col {
	position: absolute;
	top: 0;
	left: 0;
	width: 100px;
}
<!--html-->
<div id="container">
	<div id="sub_col">sub</div>
	<div id="main_col">main</div>
</div>

The sub div is not in the upper left of the container. Odd behavior.

This relates to hasLayout, an important understanding about IE. Learn about it here.

So let’s try adding hasLayout to the two inner divs. Our updated CSS:

/* css */
#container {
	position: relative;
}
#main_col {
	margin-left: 100px;
	height: 100px;
}
#sub_col {
	position: absolute;
	top: 0;
	left: 0;
	width: 100px;
	height: 50px;
}

The result:

The result did not change. The real fix is adding hasLayout to the containing, relatively positioned parent. Our updated CSS:

/* css */
#container { 
	position: relative;
	height: 150px;
}
#main_col {
	margin-left: 100px;
	height: 100px;
}
#sub_col {
	position: absolute;
	top: 0;
	left: 0;
	width: 100px;
	height: 50px;
}

And the final image:

Height isn’t necessarily the route to go to fix the parent’s woes. Many other hasLayout tricks exist, so it’s up to you to work with what’s best for your project.