CSS Box Model

Content, padding, border and margin together.

✍️ 3 exercises + code challenge in this lesson

Every element is a rectangular box made of four layers, from inside out:

  1. Content: text, images.
  2. Padding: transparent space around the content.
  3. Border: a line around the padding.
  4. Margin: space outside the border.

Calculating the size

With the default box-sizing: content-box, total width = width + left/right padding + left/right border. With box-sizing: border-box, padding and border are included in the width.

Many developers start every stylesheet with *, *::before, *::after { box-sizing: border-box; }

Key Takeaways: CSS Box Model

Mastering CSS Box Model helps you write clean and reliable CSS code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

CSS Box Model Code Example

CSS
<style>
  .box { width: 250px; padding: 20px; border: 8px solid #2563EB; margin: 15px 0; background: #DBEAFE; }
  .border-box { box-sizing: border-box; border-color: #14B8A6; background: #CCFBF1; }
</style>

<div class="box">content-box: really 306px wide</div>
<div class="box border-box">border-box: exactly 250px wide</div>
Free sign-in required · Google login available

CSS Box Model Practice Exercises

Check what you learned in “CSS Box Model”.

/ 3 solved
Fill in the blank

Include padding and border in the element's width.

* {
  box-sizing: ;
}
✓ Correct! Not quite. Try again.
Multiple choice

With content-box, width 100px, padding 10px and border 5px, what is the total width?

✓ Correct! Not quite. Try again.

100 + 2×10 + 2×5 = 130px.

Code challenge

The box should be exactly 250px wide in total, including its padding and border. Use box-sizing.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services