CSS Box Model Explained

CSS Box Model Explained

I love working with CSS in front end development both on personal projects and at Blueprint. Most things in CSS are pretty straightforward. However, one thing that can confuse developers, from beginners to even seasoned veterans, is the CSS box model. It is a concept that could be hard to grasp, just like the CSS z-index property or different units in font size. So what is the CSS box model, and why is it so confusing?

CSS Box Model

Pretty much all of HTML elements on a website are rectangular. The CSS box model describes how these elements are formatted using width, padding, border, and margin, and how these CSS properties work together. There are two types of CSS box models: traditional and W3C. In a traditional box model, padding and border are part of the width. Traditional box model was used by earlier versions of IE(<8). The W3C box model is the one recommended by the World Wide Web Consortium (W3C) and doesn't include padding and border as part of the width. Most modern browsers render the elements using the W3C box model.

Box Model Explained: Traditional vs W3C

This W3C model leads to some confusion because the box model is not very intuitive. What you perceive would be the width isn’t the actual width set in CSS. For example, one would intuitively think that a width of 200px would be applied to the whole element, but in the W3C model used by modern browsers the width of 200px is only applied to the actual content area.

There is more confusion when the width isn’t explicitly set in the CSS. In both cases, if a width of a block element isn’t set, the width of the content area will be calculated by taking the width of the parent element and subtracting the other values from the parent element’s width. Because of this, CSS resets are very useful because they get rid of those paddings and whatnot that different browsers add to elements so that elements look mostly consistent in all browsers.

CSS3 box-sizing

In CSS3, there is a new property called box-sizing that can be used to set the desired box model. There are two values for the property: border-box and content-box. Border-box renders an element using the traditional box model, and content-box renders an element using the W3C box model. If you want to use the traditional box model, you can using this code:

.foo {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
     box-sizing: border-box;
}

Conclusion

The box model is one of the important fundamentals of CSS and front end development. It may be a confusing concept to grasp, but it is necessary to understand it.

By: Blueprint

The comments are closed.

No reviews yet