The CSS Box Model

2026-10-12来源 dev.to CSSEnglish

What Is the CSS Box Model?

In CSS, every HTML element is treated like a rectangular box.

The CSS Box Model consists of four parts:

  1. Content
  2. Padding
  3. Border
  4. Margin

Let's understand each part with a simple example.

1. Content

Content is the actual information inside an element, such as text, images, or other elements.

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

Here, the content area has a width of 200px and a height of 100px by default.

2. Padding

Padding is the space between the content and the border.

div { padding: 20px; } 

Here, 20px of space is added inside the border, around the content.

3. Border

A border surrounds the content and padding.

div { border: 2px solid black; } 

Here, a solid black border with a thickness of 2px is added around the element.

4. Margin

Margin is the space outside the border. It helps create distance between an element and other elements.

div { margin: 20px; } 

Here, 20px of space is added outside the element's border.

Example: Using the Box Model

Let's combine these properties in one example.

<div class="box"> Hello World! </div> 
.box { width: 200px; padding: 20px; border: 2px solid black; margin: 20px; } 

In this example:

  • The content width is 200px.
  • The padding adds 20px on each side.
  • The border adds 2px on each side.
  • The margin creates 20px of space outside the border on each side.

原文:https://www.a8q9.cn/en/article/the-css-box-model-308410.html

相关文章