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.
<!-- A box containing the text "Content area" -->
<div class="box">Content area</div>
.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.
.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.
.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.
.box {
margin: 15px; /* Adds 15px of margin around the box */
}
CSS Box Model Exampleβ
<div class="box">Hello!</div>
.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.