The CSS Box Model

Every HTML element is a box. It might be a large box, it might be a small box, it might not look like a box, but it is still a box. With that in mind, the box model can be described as a series of boxes placed inside one another and formatted in such a way as to create the desired effect. Box models are all about the visual presentation (layout and design) of a webpage. Let's take a look at a very basic box model:

Beginning on the inside and working our way outward, we see a box containing the actual contents of a webpage, such as text, images, links, etc. The content is the most important part of the box model. The padding, border, and margin are all optional.

Padding is whitespace that fits between the content and the border so that the two do not run into one another or appear squished together.

The border can be either unspecified and invisible, or provide various visual effects that surround the content and padding.

The margin is similar to padding, except that it is outside of the border and allows the box some room to breath away from the other elements nearby.

Before you begin to think "Wow! This is too complicated!" let's take a look at how simple it is to make a box model using CSS.

p {
  padding: 15px;
  border: 1px dashed #658C00;
  margin: 30px;

Using an HTML paragraph element, and applying the above padding, border, and margin properties to that element we get the following result:

What is the difference between a guitar and a tuna fish?
You can tune a guitar but you can't tuna fish.

If you're willing to admit that box models might be a little bit easier than they seemed at first, then go ahead and take a look at the next few pages to learn more about applying padding, borders, and margins.