Saturday, July 11, 2009

How to make an element fit to it's parent?

This is an old story. Many web developers met similar problems, to make an element occupy leftover space of it's parent. Unfortunately, we are not able to do it through HTML/CSS. Some method may work for a specific browser, but it won't work for all browsers. I tried quite a few methods, none of them works for IE, Firefox and Chrome. We have to use Javascript here.
Note, when you adjust element size according to it's parent, you should be aware that offsetWidth and offsetHeight are not exactly same with style.width and style.height. See http://yijinliu.blogspot.com/2009/07/padding-and-margin.html.

How to make HTML elements resizable?

Here is a good example, http://webfx.eae.net/dhtml/genresize/genresize.html

Padding and Margin

Usually, we get an element's size by offsetWidth/offsetHeight, set them by style.width/style.height. However, these two groups are actually not same. The following stuff applies for IE/Firefox/Chrome.
As we know, an element's space is composed of padding, border, margin and client area. offsetWidth and offsetHeight are the sum of all those properties. However, style.width and style.height behaves different on different browsers. For IE, it's same with offsetWidth and offsetHeight; For Firefox and Chrome, padding is not included in style.width and style.height.