Loading...
Loading...
Understanding content, padding, border, and margin for every element
Every HTML element is a rectangular box made of four layers from inside out: content, padding (inner space), border (edge), and margin (outer space).
.box { width: 200px; padding: 20px; border: 2px solid #333; margin: 15px; }| Layer | What it does |
|---|---|
| Content | Where text and images appear |
| Padding | Space between content and border (inside the box) |
| Border | Visible edge around the element |
| Margin | Space between this element and others (outside the box) |
By default, width only sets the content width. padding and border add to it:
/* Default: width = content only. Total = 200 + 20+20 + 2+2 = 244px */
width: 200px; padding: 20px; border: 2px solid black;
/* border-box: width INCLUDES padding and border. Total = 200px */
box-sizing: border-box; width: 200px; padding: 20px; border: 2px;padding: 10px 20px 15px 25px; /* top right bottom left */
padding: 10px 20px; /* top/bottom left/right */
padding: 10px; /* all sides */| Wrong | Why | Right |
|---|---|---|
| Expecting 200px total with padding+border | Default box-sizing adds padding+border to width | Use box-sizing: border-box |
| margin: 0 auto without width | Wont center an element | Set a width first |
Create a div.card with width 250px, box-sizing border-box, padding 20px, border 3px solid #3498db (blue), margin 25px.
<!DOCTYPE html>
<html><head><style>
.card {
width: 250px; box-sizing: border-box; padding: 20px;
border: 3px solid #3498db; margin: 25px; background: #f8f9fa;
font-family: Arial, sans-serif;
}
</style></head><body>
<div class="card"><h2>Box Model</h2><p>20px padding, 3px border, 25px margin.</p></div>
</body></html>