I just discovered the box-sizing: border-box
CSS property which solves a bunch of cross browser layout problems for me.
The only issue I now have is that IE7 doesn't seem to support it. Is there a hack to get IE7 to support it?
There are several ways to do this, none perfect.
As you point out:
<!--[if IE 7]> Special instructions for IE 7 here <![endif]-->
Use box-sizing for IE8 and 9, then make specific overrides for IE7. This option will be painful.
https://github.com/Schepp/box-sizing-polyfill
This excellent Polyfill is an HTC file which modifies the default browser behavior in IE6 and 7 so they use the W3C box model. It's fine for light use, but may cause problems of it's own if used extensively. Use with caution and TEST.
The old style nested div approach is still a fine way:
<div style="width:100px; border:1px solid black"> <div style="margin:10px"> Content </div> </div>
A non-semantic nested div provides the padding indirectly, with the disadvantage that your markup becomes untidy. Obviously don't use inline styles, I'm using them here for the sake of illustration.
The old adage Never use padding on a fixed width element still stands true.
The other way round this is with the direct child selector. Say you have a fixed width div containing some content:
<div class="content"> <h1>Hi</h1> <p>hello <em>there</em></p> </div>
You can then write a rule to add left and right margins to all the direct children of the div:
.content { width:500px; padding:20px 0; } .content > * { margin:0 20px; }
This will add a little margin to the h1 and p, but not to the nested em, giving the appearance of 20px padding on the content div, but without triggering the box model bug.
IE7 is the last browser not to recognise the box-sizing property. If you're getting little traffic from IE7, you might consider dropping support. Your CSS will be much nicer.
As of late 2013, this is my preferred option.
2017 EDIT: It's probably long past time to drop support for IE7 now, and just use border-box.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With