CSS Box Model: Master Margin & Padding
Spacing is the invisible architecture of design. By mastering Margin and Padding, you control the rhythm, flow, and layout of your entire web application. Every element is a box; learn to control it.
The Inside: CSS Padding
Padding is the space between an element's content and its border. It pushes the content inward, creating "breathing room" inside the box. Crucially, padding inherits the background color of the element.
If you have a button and the text touches the edges, you don't need margin, you need padding: padding: 10px 20px; (10px top/bottom, 20px left/right).
The Outside: CSS Margin
Margin is the space outside the border. It's completely transparent and pushes other elements away. You use margin to create gaps between different sections or components on your page.
Pro-tip: Using margin: 0 auto; on a block-level element with a defined width is the oldest and most reliable trick to center it horizontally on the page.
The TRBL Shorthand
Nobody likes writing margin-top, margin-right, margin-bottom, margin-left separately. CSS provides a shorthand that works clockwise, starting from noon:
margin: 10px;(All 4 sides)margin: 10px 20px;(Top/Bottom 10px, Right/Left 20px)margin: 10px 20px 30px;(Top 10, Right/Left 20, Bottom 30)margin: 10px 20px 30px 40px;(Top, Right, Bottom, Left)
The Magic of Box-Sizing+
Default behavior is dangerous. By default, padding and border are ADDED to the width of an element (box-sizing: content-box). If your box is 100px wide, and you add 10px padding, it becomes 120px wide!
Always use * { box-sizing: border-box; }. This forces the browser to include padding and border WITHIN the 100px width you set.
❓ Frequently Asked Questions
What is the difference between Margin and Padding?
Padding: Inner space. It separates the content from the element's border. It takes on the element's background color.
Margin: Outer space. It separates the element from other surrounding elements. It is transparent.
What is "Margin Collapse"?
It is a specific CSS behavior where the vertical margins (top and bottom) of two touching block elements combine into one. Instead of being added together, the browser uses the larger margin value.
.box1 { margin-bottom: 30px; }.box2 { margin-top: 20px; }/* The actual distance will be 30px, not 50px! */Why does my padding make the box larger?
This happens because of the default box model (`content-box`). To fix it and make your CSS predictable, add this to the beginning of your stylesheet:
* {box-sizing: border-box;}