The Box Model
🎨 CSSUnderstand margin, border, padding, and content — the CSS box model.
0/5 completed
The CSS Box Model
Every HTML element is a rectangular box with four areas:
/* From outside to inside: */
/* 1. Margin — space outside the border */
/* 2. Border — the edge of the element */
/* 3. Padding — space inside the border */
/* 4. Content — the actual text/image */
.box {
width: 300px;
padding: 20px; /* inner space */
border: 2px solid #333; /* visible edge */
margin: 10px; /* outer space */
background-color: #e0e7ff;
}
📌 Important
With the default box-sizing: content-box, the total width = width + padding + border. Use box-sizing: border-box to include padding and border in the width.
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial; background: #f3f4f6; padding: 20px; }
.box {
width: 300px;
padding: 20px;
border: 3px solid #5E256D;
margin: 15px;
background: #ede9fe;
border-radius: 10px;
}
.box-small {
width: 200px;
padding: 10px;
border: 2px dashed #f59e0b;
margin: 10px;
background: #fef3c7;
}
h1 { color: #5E256D; }
</style>
</head>
<body>
<h1>Box Model Demo</h1>
<div class="box">
<strong>Purple Box</strong>
<p>margin: 15px, padding: 20px</p>
<div class="box-small">Inner Box</div>
</div>
</body>
</html>
Exercises
Exercise 1. Padding and Margin on a Card
Medium
Give the .card class a padding of 20px and a margin of 10px.
Use exactly: padding: 20px; and margin: 10px;
Use exactly: padding: 20px; and margin: 10px;
.card {
}
Expected Output
The card has 20px padding and 10px margin.