CSS box model hacks

Tuesday, November 17. 2009

CSS box model hacks

Consider that you want to display some DIV inside another DIV where the inner DIV always fills out the outer DIV completely:

<style type="text/javascript">
  #outer { width: 256px; height: 256px; }
  #inner { background: red; height: 100%; }
</style>
<div id="outer">
  <div id="inner"></div>
</div>

Width is already correct because the default value of auto keeps the inner DIV at maximum width. So only the height:100% style is needed for this scenario. But what if the inner DIV also has some padding or a border? Then the percent values will not work because according to the W3C box model the border and the padding is added to the width and height. So the inner DIV gets too large. In standard compliant browsers (Even in IE7) this can be solved pretty easy. IE6 needs a little hack. Read on...

Solution for standard browsers (And IE7+)

Instead of specifying percent values you can simply use absolute positioning and anchor the inner DIV to the edges of the outer DIV:

#outer
{
    width: 256px;
    height: 256px;
    position: relative;
}

#inner
{
    background: red;
    padding: 5px;
    border: 10px solid black;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
}

Unfortunately this does not work in IE6. If you can't ignore this dinosaur, then read on.

Solution for IE6

IE6 doesn't support specifying left/right and top/bottom pairs in absolute positioning. It prefers to use the top and left setting and ignores the other two. So we have to use width and height again and find some way to subtract the border and padding from the size.

Did you know that you can use JavaScript in CSS files? This can be used to solve our little problem. Just add these two lines to the CSS block of the inner DIV:

_width: expression(parentNode.offsetWidth - 30 + "px");
_height: expression(parentNode.offsetHeight - 30 + "px"); 

Let's exaplain: The underscore in front of the width and height settings is a very simple way for specifying CSS which is only parsed by IE. The expression simply takes the offset size of the parent node and subtracts the border and the padding from it.

This hack is ignored by IE7+ because it understands the absolute positioning and this overrides the specified size.

If you know a better way to do it, let me know!

Posted in HTML/CSS | Comments (0)

Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.