Every Element is a Box
In CSS, every HTML element is a rectangular box. That box has four layers from inside to outside:
+-------------------------------+
| margin | ← Space OUTSIDE the element
| +---------------------+ |
| | border | | ← Visible border line
| | +--------------+ | |
| | | padding | | | ← Space INSIDE the border
| | | +--------+ | | |
| | | | content| | | | ← Your actual text/image
| | | +--------+ | | |
| | +--------------+ | |
| +---------------------+ |
+-------------------------------+
Padding — Space Inside
Padding creates space between the content and the border. The background color fills the padding area.
.card {
padding: 24px; /* all 4 sides */
padding: 16px 24px; /* top+bottom | left+right */
padding: 8px 16px 24px; /* top | left+right | bottom */
padding: 8px 16px 24px 12px;/* top | right | bottom | left (clockwise) */
/* Individual sides */
padding-top: 16px;
padding-right: 24px;
padding-bottom: 16px;
padding-left: 24px;
}
Margin — Space Outside
Margin creates space between elements. Transparent — shows the background behind the element.
p {
margin-bottom: 16px; /* space below each paragraph */
}
.section {
margin: 0 auto; /* center a block element horizontally */
max-width: 800px;
}
h2 {
margin-top: 40px;
margin-bottom: 12px;
}
Border
.card {
border: 1px solid #e2e8f0; /* width | style | color */
border-radius: 12px; /* rounded corners */
border-top: 3px solid #7c3aed; /* only top border */
border-bottom: none; /* remove a border */
}
box-sizing — The Most Important Rule
By default, width only sets the content width. Padding and border get added on top, making elements bigger than expected. This drives beginners crazy.
/* WITHOUT box-sizing: element ends up 260px wide */
.card {
width: 200px;
padding: 20px; /* adds 40px */
border: 10px solid; /* adds 20px */
/* total = 260px */
}
/* WITH box-sizing: border-box — element stays 200px */
.card {
box-sizing: border-box;
width: 200px;
padding: 20px; /* included in the 200px */
border: 10px solid;
}
The fix: add this to the top of every CSS file:
*, *::before, *::after {
box-sizing: border-box;
}
Real-World Example — A Tutorial Card
.tutorial-card {
box-sizing: border-box;
width: 320px;
background: #ffffff;
border: 1px solid #e2e8f0;
border-radius: 12px;
padding: 24px;
margin: 16px;
}
.tutorial-card h3 {
margin: 0 0 8px;
font-size: 1.1rem;
}
.tutorial-card p {
margin: 0 0 16px;
color: #6b7280;
font-size: 0.9rem;
}
.tutorial-card .tag {
display: inline-block;
padding: 4px 12px;
background: #f3e8ff;
color: #7c3aed;
border-radius: 20px;
font-size: 12px;
}
Try It Yourself
- Add
*, *::before, *::after { box-sizing: border-box; }to your CSS - Create a card with padding, margin, and a border-radius
- Try setting
margin: 0 autoon a div with a fixed width to center it