CSS Box Model
What is the CSS Box Model?
The CSS box model is essentially a box that wraps around every HTML element. It consists of: margins, borders, padding, and the actual content.
Box Model Components
The box model has four parts:
- Content: The actual content of the box (text, images, etc.)
- Padding: Clears an area around the content (inside the border)
- Border: A border that goes around the padding and content
- Margin: Clears an area outside the border (space between elements)
Visual Representation
Example
div {
width: 300px;
padding: 20px;
border: 5px solid #4b3190;
margin: 30px;
}
Width and Height
When you set the width and height of an element, you're setting the width and height of the content area. To calculate the total width and height, you need to add padding, borders, and margins.
Example
.box {
width: 200px;
height: 100px;
padding: 20px;
border: 5px solid #4b3190;
margin: 10px;
/* Total width = 200 + 20*2 + 5*2 + 10*2 = 270px */
/* Total height = 100 + 20*2 + 5*2 + 10*2 = 170px */
}
Box-Sizing Property
The box-sizing property allows you to include padding and border in the element's total width and height:
Content-Box (Default)
Example
div {
box-sizing: content-box;
width: 200px;
padding: 20px;
border: 5px solid #4b3190;
/* Total width = 200 + 20*2 + 5*2 = 250px */
}
Border-Box
Example
div {
box-sizing: border-box;
width: 200px;
padding: 20px;
border: 5px solid #4b3190;
/* Total width = 200px (includes padding and border) */
}
Practical Example
Example
.card {
width: 300px;
padding: 20px;
border: 2px solid #4b3190;
margin: 20px;
background-color: white;
box-sizing: border-box;
}
Best Practices
- Use
box-sizing: border-boxfor easier sizing calculations - Understand the difference between margin and padding
- Use margins for spacing between elements
- Use padding for spacing inside elements
- Remember that margins collapse (adjacent margins combine)