Box edges and spacing
Definition and purpose
A CSS box has content, padding, border and margin areas. Padding separates content from its border; margin separates the border box from nearby boxes.
Measure four edges
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> #a { width: 100px; padding: 10px; border: 2px solid navy; margin: 8px; } </style> </head> <body> <div id="a">Sample A</div> <div id="b">Sample B</div> </body></html>The border box is 124px wide, excluding margins.
Syntax and mental model
For a content-box width of 100px, 10px padding on each side and 2px borders produce a 124px border box. Margins are outside that measurement. Four-value spacing shorthands follow top, right, bottom, left; two values set vertical and horizontal sides.
Two-value shorthand
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style>#a { padding: 8px 16px; margin: 4px 12px; }</style> </head> <body> <div id="a">Sample A</div> <div id="b">Sample B</div> </body></html>Vertical and horizontal pairs differ.
Common mistakes
Do not add margins to the border-box width itself. A border width alone does not create a visible border without a suitable border style.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Other dimensions and URL values. Next lesson: Width, height and box sizing.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Box edges and spacing — knowledge check
Five questions on box edges and spacing.
Which area lies directly inside the border?
What is the border-box width for 100px content, 10px side padding and 2px side borders?
Which is outside the border box?
What does padding: 8px 16px set on the left?
Which is needed to paint a solid border?