CSS Intro, Part 4: The Box Model

One of the vital beating hearts of CSS is its use of the Box Model.

Don’t Panic. These are merely all of the possible elements surrounding content. You don’t need to use each one every time!

In this w3C graphic, you see that the content box (determined by the height and width of the content itself) is surrounded by a padding box, which is surrounded by a border box, which is surrounded by a margin box.

This shouldn’t be much of a stretch for anyone used to the (ugly and unwieldy) HTML tables, which of course include borders, margins, and padding. Many of the concepts translate well if you imagine the CSS box as an HTML table will a single cell.

You may omit specific values for any or all of these properties, which results in a CSS box that adapts itself to the size of its content.

Border attributes include border-style, border-color, and border-width (including subsets, if needed, for border-top-width, border-bottom-width, border-right-width, and border-left-width). If you’re feeling cheeky (or simply want to conserve space), you may combine these into a single expression:

{border-width:1px 2px 3px 4px}

is exactly the same as

{border-top-width:1px

border-bottom-width:2px

border-right-width:3px

border-left-width:4px}

Many times you will not need to be this specific. If you don’t require different values for the top and bottom or either side, you may state two numbers. The first will apply to the top and bottom, and the second number will set the right and left.

This applies not only to borders but also to margins and padding as well, as in:

{border-width:2em 1em

margin:1em 2em

padding:2em 2em}

Margins will always be transparent, simply providing a space between the box and its surroundings. Padding, however, will use the same background as the content. Neither one supports custom visual properties.

Borders, on the other hand, may have a specific color value specified, using (of course) the same color names and values as any other CSS element.

When you’re not thinking about imaginary borders, and boxes. Seeing the world and getting healthy lives in the medical travel box. But it’s real and not this imaginary thing that you can only see on a computer.