Box Model
The CSS box model is a fundamental concept that describes how HTML
elements are displayed as rectangular boxes, and how the dimensions and
spacing of those boxes are calculated
The Box Model consists of four main parts:
1. Content Box
2. Padding Box
3. Border Box
4. Margin Box
1. Content Box
● It represents the area where the content of an element is displayed.
● It includes the content height and width, but not the element's total height & width.
2. Padding Box
● It is the space between the content and the border of an element.
Example:
padding: 5px;
padding: 10px;
3. Border Box
● It defines the border around an element.
Example:
border: 2px solid blue;
4. Margin Box
● It specifies the space outside an element, separating it from other elements.
Example:
margin: 5px;
margin: 10px;
Margin Shorthand Property
The margin property is a shorthand for setting margin-top, margin-right,
margin-bottom, and margin-left in a single line.
Four values:
margin: 10px 20px 30px 40px;
●
○ Top: 10px
○ Right: 20px
○ Bottom: 30px
○ Left: 40px
Three values:
margin: 10px 20px 30px;
○ Top: 10px
○ Left & Right: 20px
○ Bottom: 30px
Two values:
margin: 10px 20px;
●
○ Top & Bottom: 10px
○ Left & Right: 20px
One value:
margin: 10px;
●
○ Applies to all four sides
The same rules apply to the padding property as well.
Height and Width Calculation
The total height and width of an element include all parts of the Box Model.
Total Height Calculation
Total height = margin-top + border-top + padding-top + content-height
+ padding-bottom + border-bottom + margin-bottom
Total Width Calculation
Total width = margin-left + border-left + padding-left + content-width
+ padding-right + border-right + margin-right
Important Note:
If we specify:
height: 100px;
padding: 10px;
● The total height will be 120px (100px content + 10px padding top + 10px padding
bottom).
To fix the size of an element regardless of padding and border, use:
box-sizing: border-box;
● This ensures that padding and border are included within the specified width and height.
To remove the default margin and padding from all elements, use:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}