This is a modified version of Tantek Çelik's original box model hack, from which all things good have sprung. Check out the related blog entry, if you're interested.

Rock.

Box Model Hack, redux

Boxtest

Here is a sample div with class "boxtest".

It has 20px border, 30px padding, and 300px width.

div.boxtest { 
  border:20px solid;
  padding:30px;
  background: #ffc;
  width:300px;
}

The total width including borders and padding should be 400px.

20+30+300+30+20 = 400

User agents which misinterpret the CSS1 box model by placing border and padding inside the specified width would result in a total width of only 300px, and a content width of only 200px.

300-20-30-30-20 = 200

The red and blue bars below are there for comparison. This div (including its borders) should be as wide as the blue bar.

 
 

Content

Here is a sample div with class "content".

This div is styled almost identically to the "boxtest" div:

div.content { 
  border:20px solid;
  padding:30px;
  background: #ffc;
}

with one important addition. There is a second style rule, which takes advantage of a CSS parsing bug in IE5/Windows and IE5.5/Windows, to apply a width which is then overriden.

div.content { 
  width:400px;
  font-family: "\"}\""; 
  font-family:inherit;
  width:300px;
} 

This div (including its borders) should also be as wide as the blue bar, even in IE5/Windows and IE5.5/Windows.

In addition, we add one more rule immediately following the above style rule, to help out UAs which support CSS2 selectors and the CSS box model, but have the same parsing bug as IE5.x/Windows mentioned above. I call it the "be nice to Opera 5" rule. And be sure to not leave any space around the '>'.

html>body .content {
  width:300px;
} 

Finally, note that UAs that have the parsing bug illustrated by the "\"}\"" value, could potentially ignore the next rule, so the "be nice to Opera 5" rule serves to help those errant parsers "catch up" with where the style sheet is going.

To demonstrate that UAs' CSS parsing has recovered at this point, I added one more rule immediately after the previous one just to make it clear.


p.ruletest { color: blue }

This paragraph has class="ruletest" and thus should be colored blue. If it is red, then an earlier rule (which should have been overridden by the later one) is improperly taking effect. Note that this last style rule is unnecessary, and is only here for the purpose of illustrating that the above box model hack rules properly clean up after themselves.