Wednesday 21 February 2007

CSS: width setting for boxes different for IE and Mozilla browsers(Firefox)

Although the W3C standard is very clear on how to set and for the browser how to interpret the sizes of border, padding and width on a <DIV> IE and below has it’s own opinion about it.

W3C rules are that the width is de width of the content. So an image of 60px wide fits exactly in a <DIV>.with width: 60px. Regardless of the border and padding settings of the box.
So this 60px wide image would also fit exactly in the following <DIV>.

DIV {
width:60px;
border-style: solid;
border-width: 4px;
padding: 6px;
}

However, for this same image to fit in IE into a <DIV>, the width of that <DIV> must be width + border + padding. The CSS to make it fit in IE would then be:

DIV {
width:80px;
border-style: solid;
border-width: 4px;
padding: 6px;
}
The width is 60+2*4+2*6=80 (width + 2 borders + 2 paddings).

That was the easy part. But how can you make sure both IE and all other browsers pick up their correct CSS settings? There are several box model hacks. I choose one and it seems to be working fine.

The hack I choose hinges on the use of ‘!important’ and the property+whitespace+comment bug.
In the CSS declaration you first have to specify all border and padding properties if any. Then you put in:

width: !important;
width /**/: content width + paddings + borders;

Make sure there is a white space between ‘width’ and the comment ‘/**/’. Important is to declare the borders and padding before the ‘width’ declaration. Other declarations can be put anywhere.
In my example you would get:

DIV {
border-style: solid;
border-width: 4px;
padding: 6px;
width:60px !important;
width /**/:80px;
}

The way it works is that browsers like Firefox and Opera will implement the declaration with the !important sign and ignore the second declaration as it has less importance. Apparently IE6 implements the box model correctly but it does not use the ‘!important’ flag and also not the second declaration. However my IE version6 seems to be behaving like IE5. IE5 browser ignore the ‘!important’ but will read the second width declaration as it does not have the whitespace+comment bug.

For my purposes this hack works fine. See this link for more details and alternatives: w3pantheon

No comments: