Lesson 1: Understanding the Box Model in CSS
Overview
Most HTML elements are containers. Consider some of the HTML elements we've used so far: body, p, h1, h2, div, ul, ol, li, table, th, td. Each of these is a container, or box. Each box has three layers that surround its content. The layers are, in order from inside to outside:
- Padding
- Border
- Margin
In this lesson you will learn more about the box model, and how to work with it when applying styles to content using CSS.
Learner Outcomes
At the completion of this exercise:
- you will be able to identify the difference between margin, border, and padding in CSS.
More on the Box Model
The following illustration shows the various layers in the box model:
The size of each of the layers in the box model can be specified using the usual CSS units of measure (em, %, and px).
For example, consider the following <p>, which is wrapped inside a <div>:
<div> <p>This is a paragraph. It is a very short paragraph.</p> </div>
We can apply the following CSS to the paragraph tag in order to control the size of the padding, border, and margin of the paragraph:
div { background-color: red; padding: 0; border: 1px solid black; margin: 0; } p { background-color: white; padding: 1em; border-width: 10px; border-style: solid; border-color: blue; margin: 10px !important; }
Here's what it looks like:
Here are a few tips:
- You can specify one value for padding, border, or margin (for example, padding:5px), and that value will apply to all sides of the box.
- Alternatively, you specify a unique value for each side, such as padding-left, border-right, and margin-right.
- For padding and margin, you can use shorthand by specifying each of the four sides in a single style declaration, like this:
padding: 1em 1.5em 5% 10px;The four values are for the top, right, bottom, and left (clockwise around the box, starting at the top)
- Borders can also be specified using shorthand, like this:
border: 1px solid black;These three values represent the border-width, border-style, and border-color.
- The border-style property can have any of the following values:
- dotted
- dashed
- solid
- double
- groove
- ridge
- inset
- outset
Activities
- Be sure you understand the box model as described above. If anything's confusing, ask your instructor for help.
- Study the W3School CSS Reference. Particularly explore the Border and Outline Properties, Margin Properties, and Padding Properties. These are all properties that you can experiment with when working with your web portfolio in the next lesson. Note that each of the properties in the Reference tables includes a CSS version number, 1, 2, or 3. CSS 3 is the latest version of CSS, and has some of the coolest features, but these won't work in older browsers (in fact, some CSS3 properties won't work in newer browsers either) but you can still play with them.
Handouts/Online Documents
All done?
Proceed to Lesson 2.