CSS Box Model & Sizing
Every HTML element is a box with four layers: content, padding, border, and margin. Content holds text and images. Padding is space inside the border. Margin is space outside the border.
The Box Model
Every HTML element is a box with four layers: content, padding, border, and margin. Content holds text and images. Padding is space inside the border. Margin is space outside the border.
Real-life example: Content is a book. Padding is bubble wrap inside the box. Border is the cardboard edge. Margin is empty space between this box and the next box on the shelf.
.demo-box {
width: 200px;
padding: 20px;
border: 5px solid #0891b2;
margin: 30px;
background: #ecfeff;
}Padding & Margin
padding adds space inside the element. margin adds space outside. You can set all four sides at once or one side at a time (top, right, bottom, left).
Real-life example: padding is space between your shirt and your skin. margin is space between you and the next person in a queue.
.card {
padding: 1rem; /* all sides */
margin: 1.5rem auto; /* top/bottom 1.5rem, left/right auto */
}
.section {
padding: 2rem 1rem; /* vertical | horizontal */
margin-bottom: 3rem;
}
.no-top-gap {
margin-top: 0;
}Width & Height
width and height set the size of the content area by default. Percentages relate to the parent. Use min-height for sections that should fill the screen.
Real-life example: width and height are like setting the size of a suitcase before packing clothes inside.
.sidebar {
width: 250px;
min-height: 100vh;
}
.hero {
width: 100%;
min-height: 70vh;
}
.thumbnail {
width: 120px;
height: 120px;
object-fit: cover;
}box-sizing & max-width
By default, width does not include padding and border (content-box). box-sizing: border-box makes width include padding and border — much easier for layouts. max-width stops elements from becoming too wide on big screens.
Real-life example: border-box is like a tiffin box labeled 500ml — the label includes the walls, not just the food inside.
*,
*::before,
*::after {
box-sizing: border-box;
}
.container {
width: 100%;
max-width: 1100px;
margin-inline: auto;
padding-inline: 1rem;
}Measurement Mindset
Use px for small fixed sizes, rem for text and spacing (scales with root font size), % for fluid widths, and vh/vw for viewport-based sections.
Real-life example: rem is like measuring in cups that grow if the whole kitchen scale changes. px is a fixed ruler that never stretches.
- 1rem usually equals 16px if html { font-size: 100%; }.
- Use rem for padding and font-size so users who zoom see consistent layouts.
- Use max-width + margin: auto to center content columns.