he Box Model is one of the most important concepts in CSS.
Every single element on a webpage is treated like a box.
When you understand the box model, you understand:
Imagine every HTML element as a box made up of four layers:
+---------------------------+ | Margin | | +---------------------+ | | | Border | | | | +---------------+ | | | | | Padding | | | | | | +---------+ | | | | | | | Content | | | | | | | +---------+ | | | | | +---------------+ | | | +---------------------+ | +---------------------------+
The four parts are:
Let’s break them down.
1️⃣ Content
This is the actual text, image, or element inside the box.
Example:
<div class="box">Hello World</div>
You can control content size using:
.box {
width: 200px;
height: 100px;
}
Padding is the space between the content and the border.
.box {
padding: 20px;
}
This adds 20px space inside the box.
You can control sides individually:
.box {
padding-top: 10px;
padding-right: 20px;
padding-bottom: 15px;
padding-left: 5px;
}
Or shorthand:
padding: 10px 20px 15px 5px;
Order:
Top → Right → Bottom → Left (clockwise)
Border wraps around padding and content.
.box {
border: 3px solid black;
}
This means:
You can also customize:
border-width: 5px; border-style: dashed; border-color: red;
Margin creates space outside the border.
.box {
margin: 30px;
}
This pushes the box away from other elements.
Individual sides:
margin-top: 20px; margin-right: 10px; margin-bottom: 15px; margin-left: 5px;
Or shorthand:
margin: 20px 10px;
(Top/Bottom = 20px, Left/Right = 10px)
This is where beginners get confused.
By default:
Total Width = Width + Padding + Border
Example:
.box {
width: 200px;
padding: 20px;
border: 5px solid black;
}
Actual total width becomes:
200 (width)
Even though you set width to 200px!
To make width behave normally, use:
box-sizing: border-box;
Now:
Width includes padding and border.
Example:
.box {
width: 200px;
padding: 20px;
border: 5px solid black;
box-sizing: border-box;
}
Now the total width stays 200px.
This is the modern best practice.
HTML
<div class="box">This is a box</div>
CSS
.box {
width: 200px;
padding: 20px;
border: 5px solid blue;
margin: 30px;
background-color: lightgray;
}
What happens?
Below is the complete combined example:
<!DOCTYPE html>
<html>
<head>
<title>Box Model Example</title>
<style>
body {
font-family: Arial, sans-serif;
}
.box {
width: 250px;
height: 120px;
padding: 20px;
border: 4px solid black;
margin: 40px;
background-color: lightblue;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="box">
This box demonstrates content, padding, border, and margin.
</div>
</body>
</html>