There are multiple approaches to achieve this goal, although none are flawless.
As you have noted:
- Firefox / Opera / Safari / Chrome / IE8+ will acknowledge the box-sizing property, allowing for the use of border-boxes.
- IE6 will default to the traditional (correct?) border-box model.
- However, IE7 adopts the W3C padding box model when in standards mode, and does not support the CSS box-sizing property, making it impossible to revert to the border box model. If IE7 compatibility is necessary (which it likely still is), there are four options:
1. Conditional Comments:
<!--[if IE 7]>
Special instructions for IE 7 here
<![endif]-->
Utilize box-sizing for IE8 and 9, then implement specific overrides for IE7. This method may be cumbersome.
2. The Schepp Box Sizing Polyfill:
https://github.com/Schepp/box-sizing-polyfill
This excellent Polyfill is an HTC file that alters the default browser behavior in IE6 and 7 to adhere to the W3C box model. While suitable for light usage, it could potentially introduce issues if extensively applied. Exercise caution and thorough testing.
3. Old Style Nested Divs:
The tried-and-tested approach using nested divs persists as a viable option:
<div style="width:100px; border:1px solid black">
<div style="margin:10px">
Content
</div>
</div>
A non-semantic nested div indirectly provides the padding, albeit at the cost of untidy markup. Avoid inline styles, as they are included here solely for illustration purposes.
The age-old advice Avoid applying padding on fixed-width elements remains relevant.
4. My Preferred Solution - A Direct Child Selector:
An alternative solution involves utilizing the direct child selector. For instance, consider a fixed width div containing content:
<div class="content">
<h1>Hi</h1>
<p>hello <em>there</em></p>
</div>
You can create a rule to add left and right margins to all direct children of the div:
.content {
width:500px;
padding:20px 0;
}
.content > * {
margin:0 20px;
}
This will apply a slight margin to the h1 and p elements, while excluding the nested em element, creating the illusion of 20px padding within the content div without triggering the box model bug.
5. Consider Abandoning IE7 Support
IE7 is the final browser incapable of recognizing the box-sizing property. If your traffic from IE7 is minimal, you might contemplate dropping support. Your CSS code will benefit from significant improvements.
By late 2013, this became my favored choice.
2017 EDIT: It's likely advisable to discontinue support for IE7 now and opt for border-box exclusively.