DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

John Kennedy
John Kennedy

Posted on • Originally published at Medium on

Intro to the CSS Box Model.

I originally wrote this as a contribution to the freeCodeCamp Guide project. You can view the article as it stands here. You can read about the aims of the project in Quincy’s article from Sept 2017. Contributors to the project are always welcomed.

Understanding the CSS Box Model is crucial to being able to correctly layout a webpage.

When a browser renders (draws) a webpage each element, for example a piece of text or an image, is drawn as a rectangular box following the rules of the CSS Box Model.

At the centre of the box is the content itself, which takes up a certain height and width. This region is known as the Content Area. The size of the content area can be automatically determined, or you can explicitly set the size of height and width. (see note below regarding box-sizing)

Around the Content Area this is a region known as Padding Area. The size of the padding can be the same all around, or you can set individually for top, bottom, left and right padding. If you are using a background for the element, the background will extend into the Padding Area.

Next there is a Border Area. This creates a border around the element and its padding. You can set thickness, colour and style of the border. Style options include none, solid, dashed, dotted and several others. (see note below regarding box-sizing)

Finally there is the Margin Area. This creates clear space around the element, padding and border. Again you can individually set top, bottom, left and right margins. Under certain circumstances margin collapsing occurs and the margins between adjacent elements may be shared.

Box-Sizing Property

The default for this property is content-box. If you use the default then the box model will allow the author to specify the size of the content area. However, it is possible to use these to instead specify the size of the border area. This is done by changing box-sizing property to border-box. This can sometimes make layouts easier. You can set the box-sizing property per element as desired.

Top comments (3)

Collapse
coolgoose profile image
Alexandru Bucur

The funny part is that IE got it right and most css frameworks and tutorials suggest switching to border-box.
Here's an old, but still valid article from Paul Irish

Collapse
aleksandernt profile image
Aleksander T

Hi John. This was very useful, Thanks

Collapse
johnkennedy9147 profile image
John Kennedy Author

Glad you found it helpful.

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.