CSS3 Box-Sizing Fix for Internet Explorer 7
Roll back to quirks mode
Internet Explorer has been notorious for its peculiar rendering behavior, particular when it comes to box model, the fundamental of web layout. Its definition of box “width” is the total of inner width, padding and border width, as opposed to W3C’s standard definition of inner width only. I used to hate this (along with tons of other IE-related shenanigans) so much, but recently I started to feel that it actually makes sense and it’s quite convenient in many cases. For example, if I want to have a div
take the whole width it inherits from its parent div
, but also want it to have padding
and border
, this time IE’s box model is way easier to implement. Also, let’s admit it - W3C’s definition is quite counter-intuitive. In real world, we always measure the width of a box by its outer width, which equals the total of inner width, padding and box thickness. Good job IE, for thinking for your human users (though this might be the only case).
So CSS3 comes with box-sizing: border-box that basically allows you to roll back to IE’s box model. I just need to add “box-sizing: border-box;”, and that’s it. No more wrappers/containers that quickly make the HTML unreadable.
Of Course, Internet Explorer 7
Unfortunately, IE7 seems to be overly aggressive to get rid of its predecessors (though undoubtedly failed) and does not support it. Due the nature of my work, I still need to support this monster, but I really don’t want to add more complexity to my code. There are some plugins that utilize pollyfill to fix, but I feel there should be a better way. After some research, I came up with this little JavaScript snippet based on jQuery.
$(function(){
if (navigator.appVersion.indexOf("MSIE 7.") != -1){
$('.ie7-boxsize').each(function(){
// current outer width with padding and border
var fullW = $(this).outerWidth();
// current inner width, also the intended outer width with padding and border
var actualW = $(this).width();
// calculate the width of current padding and border
var wDiff = fullW - actualW;
// subtract padding and border from current inner width, so it shrinks
var newW = actualW - wDiff;
$(this).css('width',newW);
var fullH = $(this).outerHeight(),
actualH = $(this).height(),
hDiff = fullH - actualH,
newH = actualH - hDiff;
$(this).css('height',newH);
});
}
});
It’s quite simple: add a class .ie7-boxsize
(or whatever you want, I’m sure you can change the code) to your element, and insert this snippet to your page’s js file, remember to wrap it in document.ready or put it to the end. It should work perfectly, on both width and height.
What? How about IE6? I didn’t test on it, I just assumed it should work. But seriously, please, let’s leave that nightmare alone, unless you are designing a Chinese website.