SmartCodingTips

CSS Box Model Basics

The CSS box model is the foundation of layout and design in CSS. Every HTML element is a rectangular box made up of four parts: content, padding, border, and margin.

1. Parts of the Box Model

  • Content – The actual text or image inside the box.
  • Padding – Clears space around the content, inside the border.
  • Border – A line that surrounds the padding (and content).
  • Margin – Clears space outside the border, between this element and others.

2. Example of Box Model in Code


.box {
    width: 200px;
    padding: 20px;
    border: 5px solid #4f46e5;
    margin: 15px;
}
            

Total width = width + padding + border + margin. In this case: 200 + 40 + 10 + 30 = 280px.

3. box-sizing Property

By default, width only includes content. To include padding and border inside the defined width, use box-sizing: border-box.


* {
    box-sizing: border-box;
}
            

This makes layouts more predictable and is a common best practice.

4. Visual Layout Summary

The layout layers from inside to outside:

  • Content
  • Padding
  • Border
  • Margin

Each affects how elements are spaced and displayed on the page.

Conclusion

Understanding the box model is essential for mastering layouts in CSS. Proper use of padding, margin, and border ensures clean, responsive, and well-aligned designs.