CSS BOX Model.

One of the most important thing to understand about CSS is the Box Model. The Box Model how elements are displayed. Every element that we use in the page is considered to be a rectangular box. The properties for this box are as follow: content, padding, border and margin.

You can understand how this element interact from the following visual representation:

CSS BOX Model

As you can see the padding is applied around the content area. If we apply a background image it will be covering the area formed by the content and padding. So we can use the padding to create a gutter around the content, avoiding it to coincide exactly with the side of the background.

Then we have the border, that if applied creates a line around the padding element. We can define the number of pixels of the line, the style of the line such as solid, dashed, dotted.

After the border there is the margin. They are transparent and we can use them to create and control spacing between different boxes.

Even though the padding, borders and margins are optional and they are set to zero as default setting, usually many user agent stylesheet will give some automatic margins and padding to the elements. If we want to setting them back to zero we can use the universal selector and the following code:

*{

margin:0;
padding:0;

}

According to the W3C standard, if we assign a ‘width’ (and ‘height’) to a box, it refers to the ‘content area’ of the box only. The padding, borders, and margins are then added to this value and summing all together gives the total box width.

So if I want a box to be 100px wide, one way is to use the following values:

*{

margin: 10px;
padding: 10px;
width: 60px;

}

The reason is easy to understand:

CSS BOX Model Example

IE/WIN and the box model

Unfortunately even on the box model IE fails (as of 2008), meaning that they use their own nonstandard box model. Instead of measurig just the width of the content, IE browser calculate the width property as the sum of the width of the content, padding and borders.

IE BOX Model Example

One solution may be to never add padding to an element if we set a defined width. We may think to add padding or margins to the element’s parent or children instead.

Share
Tagged with: bordersboxCSSmarginspaddingtutorial
 

1 Response » to “CSS BOX Model.”

    Once you get to know how to approach layout with CSS then everything will seem natural that way. I actually find laying out sites using tables a bit of a bind now. I’d liken switching from tables to CSS to switching from procedural programming to OOP – you just need to change the way you solve problems.

  1. -->

Leave a Reply