🧱 Default behavior (content-box)
By default, browsers use:
box-sizing: content-box;
This means:
Total element width = content width + padding + border
So if you have:
.container {
width: 300px;
padding: 20px;
border: 5px solid black;
}
Then the total visible width becomes:
300 (content) + 40 (left + right padding) + 10 (left + right border) = 350px
⚠️ The box becomes wider than 300px, which can cause overflow or layout shifts.
✅ With box-sizing: border-box
When you use:
box-sizing: border-box;
the formula changes to:
Total element width = width (including padding + border)
So the same CSS now behaves like this:
width = 300px (total)
→ content area = 300 - (40 padding + 10 border) = 250px
✅ The box stays exactly 300px wide — no overflow.
🎯 Why it’s useful
-
Prevents unexpected overflow due to padding/borders
-
Makes responsive layouts easier
-
Keeps your box sizes consistent
-
You can trust
widthto be the actual visible width.
🌍 Common best practice
Developers often apply this globally:
* {
box-sizing: border-box;
}
So every element (and pseudo-element) uses border-box by default.
This way, your layouts behave predictably everywhere.
🧩 In your case
For your .container:
.container {
width: 80%;
margin: auto;
padding: 5em;
background-color: whitesmoke;
box-sizing: border-box; /* ✅ prevents overflow */
}
Now, even though you have padding: 5em,
the total width will stay within 80% of the parent — no horizontal scroll ✅
Would you like me to make a small side-by-side HTML example showing content-box vs border-box visually? It’ll make this concept super clear.
You said:
ChatGPT said:
Perfect 👍 Here’s a simple side-by-side example showing the difference between content-box and border-box visually.
You can copy this into any HTML file and open it in your browser 👇
🧩 HTML + CSS Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Box-Sizing Example</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
gap: 20px;
padding: 20px;
}
.box {
width: 300px;
padding: 30px;
border: 5px solid #007BFF;
background-color: lightblue;
}
.content-box {
box-sizing: content-box; /* Default */
}
.border-box {
box-sizing: border-box; /* Prevents overflow */
}
.label {
text-align: center;
font-weight: bold;
margin-top: 10px;
}
</style>
</head>
<body>
<div>
<div class="box content-box">content-box</div>
<div class="label">Total width > 300px (overflow risk)</div>
</div>
<div>
<div class="box border-box">border-box</div>
<div class="label">Total width = 300px (fits perfectly)</div>
</div>
</body>
</html>
🧠 What you’ll see:
-
The left box (
content-box) is wider than 300px because padding and border are added on top of the width. -
The right box (
border-box) is exactly 300px wide because padding and border are included in the total width.
- Get link
- X
- Other Apps
- Get link
- X
- Other Apps
Comments
Post a Comment