CSS Box Model

What Is the Box Model?

The box model describes how elements are rendered as rectangles made of:

  • Content: The actual content (text, image, etc.)
  • Padding: Clears space around the content, inside the border
  • Border: A line wrapping the element
  • Margin: Clears space outside the border, between elements

Content

The area where text or media appears. Controlled by width and height.

div {
  width: 200px;
  height: 100px;
}

Padding

Adds spacing inside the border, pushing the content inward.

div {
  padding: 20px;
}

Example:

<div style="border: 2px solid black; padding: 20px;">
  This box has 20px of padding inside the border.
</div>

Margin

Adds space outside the border, separating the element from others.

div {
  margin: 15px;
}

Example:

<div style="border: 2px solid blue; margin: 15px;">
  This box has 15px of margin outside the border.
</div>

Border

A visible line around the element, styled with width, color, and type.

div {
  border: 2px solid black;
}

Box Sizing

Use box-sizing to control how padding and border affect element size.

  • content-box: Default – width = content only
  • border-box: Includes padding and border in width
div {
  box-sizing: border-box;
}

Practice Prompt

Create a styled box using inline CSS:

<div style={{
  width: "250px",
  padding: "20px",
  border: "5px solid black",
  margin: "30px",
  boxSizing: "border-box"
}}>
  This box uses the full box model!
</div>

You can copy and paste this code in your IDE to run!

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic