Pages

Labels

Powered by Blogger.
Saturday, September 8, 2012

Box model recap

The box model is one of the cornerstones of CSS and dictates how elements are displayed and, to a certain extent, how they interact with each other. Every element on the page is considered to be a rectangular box made up of the element’s content, padding, border, and margin (see Figure 3-1).

css - Box model recap
Figure 3-1. An illustration of the box model

Padding is applied around the content area. If  you add a background to an element, it will be applied to the area formed by the content and padding. As such, padding is often used to create a gutter around content so that it does not appear flush to the side of the background. Adding a border applies a line to the outside of the padded area. These lines come in various styles such as solid, dashed, or dotted. Outside the border is a margin. Margins are transparent and cannot be seen. They are generally used to control the spacing between elements.

CSS 2.1 also contains the  outline property. Unlike the border property, outlines are drawn over the top of an element’s box, so they don’t affect its size or positioning. Because of this, outlines can be useful when fixing bugs, because they won’t alter the layout of  your page. Outlines are supported by most modern browsers including IE 8 but are not supported in IE 7 and below.

Padding, borders, and margins are optional and default to zero. However, many elements will be given margins and padding by the user-agent style sheet. You can override these browser styles by setting the element’s margin or padding back to zero. You can do this on a case-by-case basis or for every element by using the universal selector:

* {
  margin: 0;
  padding: 0;
}

Just remember that this technique is fairly indiscriminant, so it can have adverse effects on elements like the option element. As such it’s probably safer to zero down the padding and margins explicitly using a global reset.

In CSS,  width and  height refer to the width and height of the content area. Adding padding, borders, and margins will not affect the size of the content area but will increase the overall size of an element’s box. If you wanted a box with a 10-pixel margin and a 5-pixel padding on each side to be 100 pixels wide, you would need to set the width of the content to be 70 pixels (see Figure 3-2):

#myBox {
  margin: 10px;
  padding: 5px;
  width: 70px;
}

Figure 3-2. The correct box model
Figure 3-2. The correct box model

Padding, borders, and margins can be applied to  all sides of an element or individual sides. Margins can also be given a negative value and can be used in a variety of techniques.

0 Comments: