CSS Box Model

Understand how every HTML element is structured and sized.

What is the CSS Box Model?

CSS Box Model describes how every HTML element is treated as a rectangular box.

  • Defines element size
  • Controls spacing
  • Helps with layout design
  • Essential for responsive design

Real-Life Example: Think of a gift box — item inside, bubble wrap, box border, and space outside.

Parts of the CSS Box Model

  • Content – text or image inside
  • Padding – space around content
  • Border – edge around padding
  • Margin – space outside the element

Content Area

The content area holds text, images, or other elements.

Content Example


.box {
    width: 200px;
    height: 100px;
}

                

Padding

Padding creates space between the content and the border.

Padding Example


.box {
    padding: 20px;
}

                

Tip: Padding makes content more readable.

Border

The border surrounds padding and content.

Border Example


.box {
    border: 2px solid #2563eb;
}

                

Margin

Margin creates space outside the element.

Margin Example


.box {
    margin: 30px;
}

                

Note: Margins collapse vertically.

box-sizing Property

Controls how width and height are calculated.

  • content-box (default)
  • border-box (recommended)

box-sizing Example


.box {
    width: 200px;
    padding: 20px;
    border: 2px solid black;
    box-sizing: border-box;
}

                

Best Practices for Box Model

  • Use box-sizing: border-box
  • Avoid fixed heights when possible
  • Use padding for inner spacing
  • Use margin for layout spacing

Pro Tip: Mastering the box model makes layout problems disappear.