What is the box model in CSS?
sobes.tech AI
Answer from AI
The box model in CSS describes how the space occupied by an element on a web page is calculated. It includes:
- Content: The area for the actual content of the element (text, images).
- Padding: The space between the content and the border of the element.
- Border: The border surrounding the padding and content.
- Margin: The space around the border of the element, separating it from other elements.
The default size of an element (in the standard box-sizing: content-box model) is determined by the sum of the content, padding, and border sizes. Margin is added to the total occupied space but does not affect the size of the element itself.
The box-sizing: border-box property changes the calculation of the element's size to include padding and border within the total width and height. In this case, the size of the element is determined by width/height, and padding and border "consume" space from the content.
/* Standard model (default) */
.element-content-box {
width: 100px; /* Content size */
padding: 10px;
border: 5px solid black;
/* Total width: 100px (content) + 10px (padding-left) + 10px (padding-right) + 5px (border-left) + 5px (border-right) = 130px */
}
/* border-box model */
.element-border-box {
width: 100px; /* Total width: content + padding + border */
padding: 10px;
border: 5px solid black;
/* Content size: 100px - 10px (padding-left) - 10px (padding-right) - 5px (border-left) - 5px (border-right) = 70px */
}
Understanding the box model is critically important for precise positioning and layout of elements on a page.