About Lesson
What is CSS Box Model?
The CSS Box Model is a fundamental concept in web design that describes the layout of elements on a webpage. It consists of four main components: content, padding, border, and margin. Each component contributes to the total size of the box, and understanding how they interact is essential for designing and styling web layouts.
- Content: The actual content of the element, such as text, images, or other media.
- Padding: The space between the content and the element’s border. Padding helps create space around the content, providing visual separation between the content and the border.
- Border: The border of the element, which can be solid, dashed, or dotted. The border wraps around the padding and content, defining the visible boundary of the element.
- Margin: The space outside the element’s border. Margins create space between the element and adjacent elements, controlling the layout and spacing between elements on the webpage.
Syntax of CSS Box Model:
CSS
.element {
/* Content */
width: value;
height: value;
/* Padding */
padding-top: value;
padding-right: value;
padding-bottom: value;
padding-left: value;
/* Border */
border-width: value;
border-style: value;
border-color: value;
/* Margin */
margin-top: value;
margin-right: value;
margin-bottom: value;
margin-left: value;
}
Example:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>CSS Box Model Example</title>
</head>
<body>
<div class="box">
This is the content of the box.
</div>
</body>
</html>
CSS
.box {
width: 200px;
height: 150px;
padding: 20px;
border: 2px solid black;
margin: 20px;
}
In this Example:
- We have a
div
element with the class “box”. - We set the width and height of the box to 200 pixels and 150 pixels, respectively.
- We add 20 pixels of padding around the content of the box.
- We define a 2-pixel solid black border around the box.
- We add 20 pixels of margin around the outside of the border.
Here’s a diagram illustrating the CSS Box Model:
|-----------------------|
| Margin |
| ___________________ |
| | Border | |
| | _______________ | |
| | | Padding | | |
| | | | | |
| | | Content | | |
| | | | | |
| | |_______________| | |
| |___________________| |
|-----------------------|
Understanding the CSS Box Model helps you control the layout and spacing of elements on your webpage effectively.