Computer Nerd

Learn CSS 2.6: The Box Model

Learn CSS 2.6: The Box Metaphor

It's been a while since I last did a Learn CSS article or any article at all, so I'm well overdue to make one.

If you've been reading Learn CSS up to this point, you will have learned to resize and recolor objects. But if you try to create a website this way, you likely won't be satisfied with the nearly-wall-to-wall text or the fact that objects with 100% width don't actually take up 100%. Both of these issues can be resolved with a set of properties which add space outside of the edge of an element's content.

In CSS, elements are squares with a defined height and width (circles, etc. can be made by rounding corners and other tweaks). This is why the space an element takes up is called its box. The components of a box are illustrated in this image (via Wikimedia Commons):

Box model

The CSS padding: attribute specifies the size of the "padding" area of the box in terms of the width/height of each side, in the order "top, left, bottom, right." For example:

div {
    padding: 20px 40px 20px 40px

That code would add whitespace 20px tall on the top and bottom, and 40px wide on the sides. The same syntax is used for the margin: property, except that property is used to set the size of the margin, which is outside of the border.

To set the contents of the border area, you can use the border:, border-left:, border-right:, and border-top, border-bottom: properties to set the color and size of the border. border sets all borders, whereas the others set the border for one side. All of these use the format size type color, and the following types are available:

For example - if you want anything with "class=example" to have a red 4px border which is dotted at the top, dashed at the left, and solid everywhere else, the code would look like this:

.example {
    border: 4px solid red;
    border-left: 4px dashed red;
    border-top: 4px dotted red;

You can also add a round border if you use border-radius: to set the "roundness" of the border as a size.