CSS Box Model
What is the CSS Box Model?
In CSS, every HTML element is a rectangular box, and the Box Model defines how the size of these boxes is calculated and how they interact with each other. The Box Model consists of four primary parts:
1. Content Box
The content box is the area where the actual content of the element is displayed. It is defined by the width and height properties.
p {
width: 200px; /* Width of the content box */
height: 50px; /* Height of the content box */
}
Example
2. Padding
Padding is the space between the content and the border. It clears an area around the content and is entirely transparent. Here are the properties you can use: padding, padding-top, padding-right, padding-bottom, and padding-left.
p {
padding: 10px; /* Padding around the content */
}
Padding Example
3. Border
The border wraps around the padding and content. It can be styled with properties like border-width, border-style, and border-color.
p {
border: 2px solid black; /* Border around the padding */
}
Border Example
4. Margin
Margin is the space outside the border. It creates space between the element and other elements around it. Margins can be set using margin, margin-top, margin-right, margin-bottom, and margin-left.
p {
margin: 20px; /* Margin outside the border */
}
Margin Example
Box-Sizing
The box-sizing property allows to alter the calculation of the width and height of an element. The two most common values are:
content-box(default): The width and height only include the content, not included padding and border.border-box: The width and height include the content, padding, and border.
Calculating Total Width and Height
The total width and height of an element can be calculated using the following formulas:
box-sizing: content-box
- Total Width =
width+padding-left+padding-right+border-left+border-right - Total Height =
height+padding-top+padding-bottom+border-top+border-bottom
Example Calculation
p {
width: 200px;
padding: 10px;
border: 2px solid black;
box-sizing: content-box;
}
Total Width = 200px + 10px + 10px + 2px + 2px = 224px
Total Height = 200px + 10px + 10px + 2px + 2px = 224px
box-sizing: border-box
- Total Width =
width(content width =width-padding-border) - Total Height =
height(content height =height-padding-border)
Example Calculation
p {
width: 200px;
padding: 10px;
border: 2px solid black;
box-sizing: border-box;
}
- Content Width = 200px - 10px - 10px - 2px - 2px = 176px
- Content Height = 100px - 10px - 10px - 2px - 2px = 76px
Total Width = 200px
Total Height = 100px
