🎨 Day 13 — CSS Box Model, Padding, Borders & Margin
Every element on a web page is a rectangular box. The CSS Box Model describes how the size and spacing of those boxes work. Understanding this concept is key to building precise, consistent layouts.
1) The Structure of the Box Model
Each element’s box consists of:
Content – the actual text or image inside the box.
Padding – the space between the content and the border.
Border – the line surrounding the padding (optional).
Margin – the space outside the border, separating boxes.
.box {
width:200px;
padding:20px;
border:5px solid #4caf50;
margin:15px;
}
2) Total Width & Height Calculation
By default, the total width = content + padding + border + margin.
/* Example */
width: 200px;
padding: 10px;
border: 5px solid;
margin: 20px;
/* Total element width = 200 + (10×2) + (5×2) = 230px + margins */
3) The box-sizing Property
It changes how total size is calculated:
content-box (default) – width = content only.
border-box – width includes padding & border ( easier layouts ).
* { box-sizing: border-box; } /* Common reset */
4) Padding — Inner Spacing
Applies inside the border, around content.
Can be set individually: padding-top, padding-right, etc.
Shorthand: padding: top right bottom left;
.box { padding: 10px 20px; }
5) Border — The Box Outline
Controls thickness, style, and color around padding.
.box {
border-width: 4px;
border-style: solid;
border-color: #4caf50;
}
/* shorthand */
border: 4px dashed #ff9800;
6) Margin — Outer Spacing
Controls space between elements (outside border).
Can be set individually like padding.
Margin collapse: vertical margins between blocks may merge into a single margin equal to the largest one.
h1, h2 { margin: 20px 0; } /* top and bottom spacing */
7) Live Demo — Try the Box Model
Run Code
8) Practice Tasks
Create three div boxes with different padding and margin values. Observe spacing changes.
Apply different border styles (solid, dotted, double) to compare effects.
Use box-sizing: border-box; and note how it simplifies layout width calculations.
Experiment with margin collapse by stacking two paragraphs and adjusting their margins.
Project of the Day
Build a simple card layout using the Box Model. Each card should have:
padding for inner spacing,
a border around the card,
margin to separate cards,
use box-sizing: border-box; to simplify widths.
Comments
Post a Comment