Box model
Elements on a page form boxes - rectangular areas containing the element content. Each box also has padding, border, and margin areas, as shown in the graphic below:
For example:
<p style="border: solid black 1px;">Content</p>
The above style would create a black border around the paragraph content.
<p style="border:
solid black 1px;
padding: 8px; margin: 10px">Content</p>
Adding a "padding: 8px" property would put eight pixels of space between the content and the border. The "margin: 10px" property would provide ten pixels of space outside the border.
Listing dimension values
Each element has four sides. The values for margin and padding can be different for each side.
- padding: 10px; — A single value means that all four sides have the same dimension.
- padding: 10px 5px; — Two values mean that the top and bottom sides have the first value and the right and left sides have the second value.
- padding: 10px 5px 15px 5px; — Four values means that each of the sides has its own dimension, assigned from the top clockwise around the element (top, right, bottom, left).
Vertical margins collapse
When two elements are one above the other, the margin between them will collapse to the value of the larger of the two margins.
Margins, Borders, and Padding Exercise
Go to this example page and use the Web Developer's Toolbar tools to manipulate the margin, border, and padding values to see how they interact.
More information
- The Box Model — W3C