All HTML elements can be considered as 'boxes'. In CSS, the term "Box Model" is used when talking about design and layout. It consists of four distinct levels: Margins, Borders, Padding, and the Content area.
Imagine your element is a framed picture. Each layer of the box model serves a specific purpose:
Surrounded by Padding, Border, and Margin.
By default, when you set the width of an element, it only applies to the content area. To get the total width of the element, you must add the padding and borders on both sides.
div {
width: 300px;
padding: 10px;
border: 5px solid gray;
margin: 20px;
}
/* Total width = 300 + 10(L) + 10(R) + 5(L) + 5(R) = 330px */
box-sizing SolutionTo keep the total width exactly what you specified, you can use box-sizing: border-box;. This automatically shrinks the content area to accommodate any padding or borders.
* {
box-sizing: border-box; /* Modern standard */
}
div {
width: 300px;
padding: 10px;
border: 5px solid gray;
}
/* Total width remains 300px */
box-sizing: border-box; in your universal selector (*) for easy responsive layouts.