CSS Box Model

Look At That Box!

If you use CSS and your not familiar with "The Box Model", you can end up with some unexpected results and experience frustration trying to figure out why its not working they way you envisaged.

The box model my appear to be intuitive, and it is except for a couple of points. Here's a quick intro and overview.

The Box Model is essentially made up of 4 parts. Starting in the center and working out:

Content -> Padding -> Border -> Margin

Content

Content is... where you put your content. Text, image, title, hyperlink, list, you know the usual kinda stuff.

Padding

Padding is the space or distance between content and the border. Its how far content is moved away from the border.  By default padding is set to zero and there's no distance between content and border.

Border

Border is the outline you can see around your content. It can be visible if its given a width and color. If not, by default its not visible.

Margin

Margin the distance between the outside edge of the border and any other entity.  Margin is transparent.


If you have been working on a layout and the design will not fit, its probably down to the box model. A frequently overlooked fact is that all the width are added together for a total width for your box element.

The same applies to the height of the box.

For example if you have content set to a width of 100px, padding set to 10px, border set to 5px and margin of 10px. The overall width of your box is 150px.

It works like this:

margin + border + padding + content + padding + border + margin = total width

10 + 5 + 10 + 100 + 10 + 5 +10 = 150px total width.

It easy to overlook this when coding your CSS.

Done!