Skip to main content
Practice

Box Model

The Box Model is a CSS structure that considers each element on a web page as a box.

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

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

  • Content: The chocolates inside the box (the area where the actual content is located)

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

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

  • Margin: The space between the chocolate box and other chocolate boxes (the space between other elements)


Let's take a closer look at each component of the box model.


Components​

1. Content​

Content is the part that is actually visible on the web page, such as text or images.

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

2. Padding​

Padding refers to the space between the content and the border.

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

3. Border​

The border is the boundary line of the box. You can specify the thickness, style, and color of the border using CSS.

CSS
.box {
border: 5px solid black; /* A black border of 5px thickness with a solid style */
}

4. Margin​

Margin refers to the space outside the border, creating separation between this element and others.

CSS
.box {
margin: 15px; /* Adding 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;
}

Following the CSS code, the div element with the class .box has the following characteristics:

  • Content saying "Hello!"

  • 20px of padding between the content and the border

  • A border with 5px thickness in blue color

  • 15px of margin outside the border


Type in the highlighted parts of the code for emphasis.

Want to learn more?

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