Saturday, April 11, 2015

box-sizing: border-box;

One of the biggest pains in a web development, apart from vertical centering (except for inside a table cell), is a W3C box model, which doesn't include padding and borders into the width. You can't use "padding: 10px; width: 100%;", because the element will be 20px wider, than the parent element.

Fortunately, in CSS3 there's box-sizing property. Default value is "content-box", which behaves as the W3C model, but if you set the property to "border-box", it solves the problem with padding/border and the width. I noticed almost all major CSS frameworks adds this property to every element, like this:

* {
    box-sizing: border-box;
}


In the past (in terms of internet it was more like an ancient history), comparable pain was an old Internet Explorer's own box model concept, which included border and padding into the width (so  basically like "box-sizing: border-box"), whilst Netscape Navigator (ancestor of Firefox) followed W3C standards.

Side note: I don't like Microsoft doing stuff his own way, but this was actually better, than standards.

Anyway, when designing a web page you had to hack this differences, usually by using two divs instead of one. Outer div had the 100% width, inner div had the padding and border. Width of the inner div has been calculated automatically. And this wasn't the worst hack at the time, webdesign was often close to a witchcraft :-)

Microsoft added "standard mode" (now we call it "almost standard") into IE6, but kept so called "quirks mode" default and switching of those modes has been guided by DOCTYPE. This changed with IE7, where W3C mode became default (according to my test in IE11 dev tools).

Now, if you use HTML5 doctype <!DOCTYPE html>, you will get the best results - so use it always!

And about the vertical centering, you can use display property with CSS2.1 value "table-cell", so even div can behave like a table cell, with working vertical-align: middle, like this:

.verticenter {
    display: table-cell;
    vertical-align: middle;
}


But don't forget you should to make it a proper table! So parent div will have "display: table-row;" and it's parent div will have "display: table;". Happy styling!

No comments:

Post a Comment