55 Mins

10. The CSS Box Model

CSS Architecture

This is the single most important concept in CSS. Every HTML element is a rectangular box. Even a round button is calculated as a rectangle by the browser. Understanding the box model is the key to controlling spacing in your layouts.

The 4 Layers

From inside to outside, every element has four layers: Content → Padding → Border → Margin

<style> .box { width: 200px; background: #4FC3F7; padding: 20px; /* space inside, between content and border */ border: 4px solid #0077CC; margin: 30px; /* space outside, pushing other elements away */ color: white; font-family: sans-serif; font-weight: bold; } </style> <div class="box">I am the content. Padding wraps me. Border wraps the padding. Margin is the outer space.</div>

Padding Shorthand

<style> .p1 { padding: 20px; background:#e3f2fd; margin:5px; } /* all 4 sides */ .p2 { padding: 10px 30px; background:#e8f5e9; margin:5px; } /* top/bottom left/right */ .p3 { padding: 5px 15px 25px 10px; background:#fff3e0; margin:5px; } /* top right bottom left */ </style> <div class="p1">padding: 20px — all sides equal</div> <div class="p2">padding: 10px 30px — vertical | horizontal</div> <div class="p3">padding: 5px 15px 25px 10px — top right bottom left</div>

Borders

<style> .b1 { border: 2px solid black; padding:10px; margin:8px; } .b2 { border: 3px dashed #1037c3; padding:10px; margin:8px; color:#1037c3; } .b3 { border: 4px double #764ba2; padding:10px; margin:8px; color:#764ba2; } .b4 { border-bottom: 2px solid #28a745; padding:10px; margin:8px; color:#28a745; } .b5 { border-radius: 50px; border: 2px solid #dc3545; padding:10px; margin:8px; color:#dc3545; text-align:center; } </style> <div class="b1">border: 2px solid black</div> <div class="b2">border: 3px dashed blue</div> <div class="b3">border: 4px double purple</div> <div class="b4">border-bottom only (underline style)</div> <div class="b5">border-radius: pill shape</div>

box-sizing: border-box

By default, padding and border are added onto your width. A 200px element with 20px padding becomes 240px! Fix this globally with box-sizing: border-box:

<style> * { box-sizing: border-box; margin: 0; padding: 0; } .without { width: 200px; padding: 20px; background: #ff6b6b; color: white; margin: 5px; } .with { width: 200px; padding: 20px; background: #51cf66; color: white; margin: 5px; } </style> <div class="with">box-sizing: border-box (width stays 200px even with padding)</div> <!-- Both are set to width: 200px, but border-box respects that -->
Always put * { box-sizing: border-box; } at the very top of every CSS file. Every professional does this.

Knowledge Check

Ready to test your understanding of 10. The CSS Box Model?

Back