Throughout our HTML Basics tutorial, we referred to HTML elements as "containers," because most of them are meant to hold things like content or other HTML elements. However, CSS takes that concept a step further. When it comes to CSS, every HTML element is considered to be a box with distinct layers. This concept is called the box model.
Every block-level HTML element you put on a webpage is a box, even if it doesn't ordinarily look like it. For example, if you add a
<p> element to your webpage and load it, it initially looks like it's just loose text. If you add some CSS colors, though, you can see the square box shape:
The box model defines the different parts of that shape, which are broken up into four pieces, or sub-boxes:
<p>element, for example, this is the area where text would be displayed. In the image above, it's the entire area made visible with the background color.
You may not always style all four of these sub-boxes, so they may not always be visible. Regardless, they are part of the make-up of every block-level HTML element.
Inline HTML elements are still boxes, but they don't respect all of the box model behavior and aren't as flexible. You'll get a feel for the differences over time, but in general, inline elements are incompatible with any CSS that would disrupt the basic flow of a line of text.
Most of the CSS we've worked with so far has been concerned with the content of HTML elements, so that is most of what you've seen. However, it's important to recognize that the content is only part of the series of boxes that makes up each HTML element.
In particular, let's consider the height and width declarations you can use to resize HTML elements. While at first glance they may appear to resize an element as a whole, they are actually only resizing an element's content. The padding, border, and margin boxes can be resized separately from the content. Take this paragraph as an example:
It has been styled to add to the padding and border and make them visible. Now let's add a
height: 50px; declaration to it:
Notice that while the content box has increased in size, the padding and border boxes have remained the same.
We'll talk about margins, borders, and padding in more detail in the following lessons, but try adding each of these declarations, one by one, to the input below:
background-color: #15AAD7; color: white; padding: 10px; border: solid 3px #0F7391; margin: 10px;
The selector for the ruleset is already defined for you, and targets the paragraph to its right. Once you've tried those declarations, try changing some of the values yourself. For example, try using different values for the
margin values, or try changing the "solid" value in your
border declaration to "dashed" or "dotted". Remember to click Update CSS to apply the changes.
Congratulations, you've explored the box model on your webpage!