CSS Box Model Basics
CSS Layouting - 5 Box Model _ Padding, Border & Box Sizing
The CSS Box Model is the foundation of layout in CSS. It defines how elements are structured
and spaced on a webpage. The key components of the box model are:
1. Content – The actual content of the box (text, image, etc.).
2. Padding – Space between the content and the border.
3. Border – A surrounding line around the padding and content.
4. Margin – Space outside the border separating elements.
5. Box Sizing – Determines how the box dimensions are calculated.
1. Padding
Padding controls the space inside the element, between the content and the border.
css
.box {
padding: 20px; /* Applies 20px padding on all sides */
}
Padding can also be set for each side separately:
css
.box {
padding-top: 10px;
padding-right: 15px;
padding-bottom: 20px;
padding-left: 25px;
}
1/3
2. Border
The border wraps around the padding and content, defining the element's visible edge.
css
.box {
border: 2px solid black; /* 2px width, solid style, black color */
}
Borders can be customized per side:
css
.box {
border-top: 5px dashed red;
border-right: 3px solid blue;
border-bottom: 4px double green;
border-left: 2px dotted purple;
}
3. Box Sizing
By default, the width and height only apply to the content, but box-sizing controls how
padding and borders are included.
Default ( content-box ): The width excludes padding and border.
border-box : The width includes padding and border.
css
.box {
width: 200px;
padding: 20px;
border: 5px solid black;
box-sizing: border-box; /* Ensures total width remains 200px */
}
2/3
4. Example of Box Model
css
.box {
width: 300px;
padding: 20px;
border: 5px solid blue;
margin: 10px;
box-sizing: border-box;
}
Visual Breakdown (using border-box ):
Total width = 300px (since padding & border are included)
Content width = 300px - (2 × 20px padding) - (2 × 5px border) = 250px
5. Illustration of the Box Model
lua
+---------------------------------+ (Margin)
| +-------------------------+ | (Border)
| | +-------------------+ | | (Padding)
| | | Content | | | (Content)
| | +-------------------+ | |
| +-------------------------+ |
+---------------------------------+
Would you like a working example using HTML & CSS? 🚀
3/3