ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

CSS3 Tutorial• 5 min read

The CSS Box Model

Margins, borders, padding, and content width/height

All HTML elements can be considered as boxes. In CSS, the term "box model" is used when talking about design and layout.

Components of the Box Model

Content: The content of the box, where text and images appear.

Padding: Clears an area around the content. The padding is transparent and takes the background color.

Border: A border that goes around the padding and content.

Margin: Clears an area outside the border. The margin is completely transparent and pushes sibling elements away.

Box Model in Practice
<div style="
  box-sizing: border-box;
  width: 300px;
  background-color: #ecfdf5;
  border: 4px solid #04AA6D;
  padding: 24px;
  margin: 30px auto;
  border-radius: 12px;
  font-family: sans-serif;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
">
  <h3 style="margin-top: 0; color: #065f46;">Box Model Card</h3>
  <p style="color: #047857; margin-bottom: 0;">
    Notice how padding expands inner space, the green border wraps it, and margin separates it from outer elements.
  </p>
</div>
Pro Tip

Always set box-sizing: border-box; on all elements (* { box-sizing: border-box; }). This ensures padding and border are included in the element's total width and height, preventing layout breakage!

ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which layer of the CSS Box Model creates space OUTSIDE of an element's border?