New here? Start with the essentials and go from there.

Wednesday, May 6, 2009

IE7 Fun Fact: Cannot calculate percentage of absolute element

We all know that IE6 has trouble doing percentage heights and widths of implicitly-sized elements, and also that it does not accept, say, “top: 0; bottom: 0;” on an absolutely-positioned element to give it the height (including padding) of its container. IE7 fixes both of these bugs, but still has a problem with the combination.

Here’s the example:


There’s an outer red element (positioned absolutely with top, left, bottom, and right at 0) that should be entirely obscured by the green element, which is statically positioned with height of 100%. In IE7, however, the green element is only as tall as the line height.

IE7 is unable to calculate the percentage (“100%”) of an absolutely-positioned element that is sized by setting its top / left / bottom / right properties. Unfortunately, it appears that no combination of hasLayout or overflow or anything will sort this out.

The solution is to sully ourselves by resorting to the ultimate hack, an expression.

When we add the following code, IE7 behaves:

height: expression(this.parentNode.clientHeight)

Unfortunately, parentNode.clientHeight and height: 100% are not equivalent when the parent has padding. clientHeight includes it, whereas the percentage does not (when the element is positioned statically, that is).

Here’s a padding example, which should have a nice five pixel red border around it.


Solving this entirely correctly with an expression is not really practical, as it will require looking up calculated styles and the like. Nevertheless, we can cheat if we assume that the container’s padding will be symmetrical. We then just say:

height: expression(this.parentNode.clientHeight - 2 * this.offsetTop)

As long as the top and bottom padding are the same (offsetTop is an effective measure of the top padding) this will look ok:

0 comments:

Post a Comment

Blog Widget by LinkWithin