CSS Box Model
CSS Box Model
The CSS Box Model is a fundamental concept in web design that describes how elements are
structured and spaced on a webpage. Every HTML element is considered as a rectangular
box, comprising the following areas:
📐 Visual Representation
lua
+---------------------------+
| Margin |
| +---------------------+ |
| | Border | |
| | +---------------+ | |
| | | Padding | | |
| | | +---------+ | | |
| | | | Content | | | |
| | | +---------+ | | |
| | +---------------+ | |
| +---------------------+ |
+---------------------------+
By default, the total width and height of an element are calculated as:
Total Width = content width + left padding + right padding + left border
+ right border + left margin + right margin
Total Height = content height + top padding + bottom padding + top border
+ bottom border + top margin + bottom margin
To include padding and border within the specified width and height of an element, you can
use the box-sizing property:
css
* {
box-sizing: border-box;
}
With box-sizing: border-box;, the total width and height of the element include content,
padding, and border, simplifying layout calculations. This approach is widely adopted in
modern web design.
Understanding the CSS Box Model is crucial for designing and positioning elements
effectively on a webpage. If you'd like, I can provide a printable PDF version of these notes
or include a real-world example to illustrate how the box model works in practice. Let me
know!
css
.box {
width: 300px;
height: 150px;
}
� Padding
Padding creates space inside the element, between the content and the border.
Individual Sides:
css
.box {
padding-top: 10px;
padding-right: 15px;
padding-bottom: 10px;
padding-left: 15px;
}
Shorthand:
css
.box {
padding: 10px 15px 10px 15px; /* top right bottom left */
}
Shorthand Variations:
� Margin
Margin creates space outside the element, separating it from other elements.
Individual Sides:
css
.box {
margin-top: 10px;
margin-right: 15px;
margin-bottom: 10px;
margin-left: 15px;
}
Shorthand:
css
.box {
margin: 10px 15px 10px 15px; /* top right bottom left */
}
Shorthand Variations:
� Border
Individual Sides:
css
.box {
border-top: 2px solid black;
border-right: 2px solid black;
border-bottom: 2px solid black;
border-left: 2px solid black;
}
Shorthand:
css
.box {
border: 2px solid black; /* width style color */
}
Note: Unlike margin and padding, the border shorthand applies the same style to all sides.
To set different styles for each side, use the individual properties.
Top
Right
Bottom
Left
This helps recall the sequence when using four values in shorthand properties.
To include padding and border within the specified width and height, use:
css
* {
box-sizing: border-box;
}
This sets the box-sizing property to border-box, which adjusts the box model calculation
accordingly.