Table of Contents
Understanding the CSS Box Model
The CSS box model is fundamental to understanding how elements are sized and spaced on a webpage. Every HTML element is essentially a rectangular box.
Box Model Components
From inside to outside:
- Content - The actual content (text, images, etc.)
- Padding - Space between content and border
- Border - The border around the padding
- Margin - Space outside the border
Box Model Properties
Padding
/* All sides */
padding: 20px;
/* Top/bottom, left/right */
padding: 10px 20px;
/* Top, right, bottom, left */
padding: 10px 15px 20px 25px;
/* Individual sides */
padding-top: 10px;
padding-right: 15px;
padding-bottom: 20px;
padding-left: 25px;
Border
/* Shorthand */
border: 2px solid #333;
/* Individual properties */
border-width: 2px;
border-style: solid;
border-color: #333;
/* Individual sides */
border-top: 1px solid red;
border-radius: 5px; /* Rounded corners */
Margin
/* Same syntax as padding */
margin: 20px;
margin: 10px 20px;
margin: 10px 15px 20px 25px;
/* Auto centering */
margin: 0 auto;
Box-Sizing Property
/* Default behavior */
box-sizing: content-box;
/* Width = content width only */
/* Modern approach */
box-sizing: border-box;
/* Width = content + padding + border */
/* Apply to all elements */
* {
box-sizing: border-box;
}
Practical Example
<style>
.box {
width: 300px;
height: 200px;
padding: 20px;
border: 5px solid #333;
margin: 30px;
background-color: #f0f0f0;
box-sizing: border-box;
}
.content-box {
box-sizing: content-box;
/* Total width: 300 + 40 + 10 = 350px */
}
.border-box {
box-sizing: border-box;
/* Total width: 300px (includes padding and border) */
}
</style>
<div class="box border-box">
This box uses border-box sizing
</div>