Every element on a web page is a rectangular box and can be modified using CSS properties. This tutorial aims to provide an understanding of how the CSS Box Model works and how to use it effectively in your web designs.
In this tutorial, you will learn about:
- The CSS Box Model
- Its components: margins, borders, padding, and content
- How to manipulate these components using CSS
Prerequisites: Basic understanding of HTML and CSS.
The CSS Box Model comprises four parts:
The content of the box, where your text, images, or other media live. Its dimensions are controlled by the width
and height
properties.
div {
width: 320px;
height: 200px;
}
This CSS sets the width and height of the div
content area.
Padding is the space that's inside the element but outside the actual content. To set the padding, use the padding
property.
div {
padding: 10px;
}
This CSS adds 10 pixels of padding around all sides of the div
content area.
Surrounding the padding (if any), you might find a border. This is controlled by the border
property.
div {
border: 1px solid black;
}
This CSS adds a solid, 1 pixel, black border around the padding and content.
Margin is the space around the element. The larger the margin, the more space between our element and the elements surrounding it.
div {
margin: 20px;
}
This CSS adds 20 pixels of margin around the div
.
Let's create a box with specific margin, border, padding, and content.
<div class="box">Content</div>
.box {
width: 200px;
height: 200px;
padding: 50px;
border: 5px solid black;
margin: 20px;
}
In this example, we have a div with a class of box
. The box's content area will be 200px wide and 200px high. There will be 50px of padding between the content and the border. The border itself will be 5px wide. And finally, there will be 20px of margin outside the border.
In this tutorial, we've learned about the CSS Box Model and its four components: content, padding, border, and margin. Understanding these elements and how they interact with each other is essential for controlling layout and alignment in your CSS designs.
Next steps for learning would be exploring how to control box sizing, especially with the box-sizing
property, and understanding how these elements affect the positioning of other elements on the page.
Additional resources:
- MDN CSS Box Model
- W3Schools Box Model
Solution:
<div class="box">Content</div>
.box {
width: 150px;
height: 150px;
padding: 25px;
border: 2px solid black;
margin: 10px;
}
Solution:
<div class="box">Content</div>
.box {
width: 120px;
height: 120px;
padding: 40px;
border: 3px dotted black;
margin: 30px;
}
For further practice, try to manipulate these properties on different elements and observe how they interact with each other and affect the overall layout.