Box Model Layout

CSS layout represents each Web page element using the box model, which treats each element as a rectangular box with several global properties. Before CSS exist, people create web site using tables so that you can display things side-by-side and lay all the web page elements as you would like them to be. However, table is not flexible or fluid enough to control the elements of the web site.

There are a few important things to consider to use the box model effectively:

  1. Differentiate between margin, border, and padding. These three things create space around the contents of a Web page element, so it is important to understand how one affects the others to accomplish the layout that you want.

    Border can have width, style, and color that you specify, is the only one that can be seen in a Web browser. It serves as a reference point for padding and margin.

    Padding is the space inside a border between the element content and the border, while margin is the space outside the border between the adjacent or parent elements and the border.
    Box Model shows padding, border, and margin of 1em each
  2. Calculate the box size. The size of the padding, border, and margin will increase the amount of real estate on a Web page that an element resides. You specify their dimension using width and height.
    The total horizontal area occupied by this element on the Web page is: 1em + 1em + 1em + 11em + 2em + 1em + 1em = 18em. Later, you will need to substract 18em from the container wrapping this element.
    Sample image on calculating box model of an element
  3. Shorthand combining properties.
    box model # of values apply to shorthand examples equal to
    padding four top, right, bottom, left margin: 0 1em 2em 0; margin-top: 0;
    margin-right: 1em;
    margin-bottom: 2em;
    margin-left: 0em;
      three top, left/right, bottom margin: 0 2em 1em; margin-top: 0;
    margin-right: 2em;
    margin-bottom: 1em;
    margin-left: 2em;
      two top/bottom, left/right margin: 1 2em; margin-top: 1em;
    margin-right: 2em;
    margin-bottom: 1em;
    margin-left: 2em;
      one top/left/bottom/right margin: 1em; margin-top: 1em;
    margin-right: 1em;
    margin-bottom: 1em;
    margin-left: 1em;
    border three width, style, color border: 2px solid blue; border-width: 2px;
    border-style: solid;
    border-color: blue;
    margin four top, right, bottom, left padding: 0 1em 2em 0; padding-top: 0;
    padding-right: 1em;
    padding-bottom: 2em;
    padding-left: 0em;
      three top, left/right, bottom padding: 0 2em 1em; padding-top: 0;
    padding-right: 2em;
    padding-bottom: 1em;
    padding-left: 2em;
      two top/bottom, left/right padding: 1 2em; padding-top: 1em;
    padding-right: 2em;
    padding-bottom: 1em;
    padding-left: 2em;
      one top/left/bottom/right padding: 1em; padding-top: 1em;
    padding-right: 1em;
    padding-bottom: 1em;
    padding-left: 1em;