Skip to main content
Practice

Box Model

The Box Model is a CSS structure where each element on a web page is thought of as a box.

This box consists of four parts: content, padding, border, and margin.

Let's compare the box model to a box of chocolates. 🍫

  • Content: The chocolates inside the box (area occupied by the actual content)

  • Padding: The space between the chocolates and the box edge (space between content and border)

  • Border: The box itself (the border of the box)

  • Margin: The space between this chocolate box and other chocolate boxes (spacing with other elements)


Let’s delve deeper into each component of the box model.


Components​

1. Content​

Content refers to the part of the web page that is actually visible, such as text and images.

HTML
<!-- A box containing the text "Content area" -->
<div class="box">Content area</div>
CSS
.box {
width: 200px; /* Sets the width of the box to 200px */
height: 100px; /* Sets the height of the box to 100px */
}

2. Padding​

Padding is the space between the content and the border.

CSS
.box {
padding: 20px; /* Adds 20px of padding to all sides (top, right, bottom, left) */
}

3. Border​

The border refers to the boundary line of the box. You can set the thickness, style, and color of the border with CSS.

CSS
.box {
border: 5px solid black; /* A 5px thick, solid, black border */
}

4. Margin​

Margin is the outer space of the border, creating a gap between the box and other elements.

CSS
.box {
margin: 15px; /* Adds 15px of margin around the box */
}

CSS Box Model Example​

HTML
<div class="box">Hello!</div>
CSS
.box {
width: 100px;
height: 100px;
padding: 20px;
border: 5px solid blue;
margin: 15px;
background-color: yellow;
}

According to the CSS code, a div element with the .box class has the following properties:

  • Content: "Hello!"

  • Padding: 20px between the content and the border

  • Border: A 5px thick blue border

  • Margin: 15px of outer space beyond the border


Try typing the emphasized parts of the code.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.