Box Model, Borders & Spacing
The Box Model
Every HTML element is rendered as a rectangular box, made up of four layers, from the inside out:
- Content — the actual text or image
- Padding — space between the content and the border
- Border — a line around the padding
- Margin — space outside the border, between this box and others
.box {
width: 300px;
height: 150px;
padding: 20px;
border: 5px solid black;
margin: 10px;
}
By default, width and height set the size of the content only —
padding and border are added on top, making the box bigger than you specified. Most modern
stylesheets fix this with box-sizing: border-box (covered in the last chapter of
this course), which makes width/height include padding and border instead.
Borders
.box {
border-width: 2px;
border-style: solid; /* solid | dashed | dotted | double | none */
border-color: #C41230;
/* Shorthand */
border: 2px solid #C41230;
/* Individual sides */
border-top: 1px solid black;
border-right: 2px dashed gray;
/* Rounded corners */
border-radius: 8px;
border-radius: 50%; /* makes a circle, on a square box */
}
Margin
.box {
margin-top: 10px;
margin-right: 15px;
margin-bottom: 10px;
margin-left: 15px;
/* Shorthand: top right bottom left (clockwise) */
margin: 10px 15px 10px 15px;
/* Shorthand: vertical horizontal */
margin: 10px 15px;
/* Same on all sides */
margin: 10px;
/* Center a block element horizontally */
margin: 0 auto;
}
Margin collapse: when two vertical margins meet (e.g. the bottom margin of one paragraph and the top margin of the next), they don't add together — the browser uses whichever is larger. This only happens with vertical margins in normal document flow.
Padding
.box {
padding-top: 10px;
padding-right: 15px;
padding-bottom: 10px;
padding-left: 15px;
/* Same shorthand pattern as margin */
padding: 10px 15px 10px 15px;
padding: 10px 15px;
padding: 10px;
}
Unlike margin, padding never collapses and can never go negative.
Outline
An outline looks similar to a border, but it doesn't take up space in the box model — it's drawn on top, outside the border, without pushing other elements around. It's commonly used for accessible focus indicators.
button:focus {
outline: 3px solid #F5A623;
outline-offset: 2px; /* gap between border and outline */
}