What is the Box Model?
The CSS box model describes the rectangular boxes generated for elements in the document tree. It consists of:
- Content: The actual content of the box (e.g., text, images).
- Padding: Space between the content and the border.
- Border: A border surrounding the padding (or content if no padding).
- Margin: Space between the border and other elements.
Example: Box Model
/* Example */
div {
width: 200px;
padding: 20px;
border: 5px solid black;
margin: 10px;
}
This example creates a box with content, padding, border, and margin.
Box-Sizing Property
The box-sizing property controls how the width and height of an element are calculated:
- content-box: Default value. Width and height include only the content.
- border-box: Width and height include content, padding, and border.
/* Example */
div {
box-sizing: border-box;
}
This example ensures the total width and height include padding and border.
Practice
Try experimenting with the box model:
- Adjust padding, border, and margin values to see their effects.
- Use
box-sizing: border-boxfor consistent layouts. - Combine box model properties with responsive design techniques.
Continue Learning
Quick Check
Which part of the box model is the space between the content and the border?