Every element in CSS is a rectangular box. The box model describes how the size of each element is calculated from four layers: content, padding, border, and margin.
The box-sizing property controls how width and height are calculated.
Width and height only apply to the content area. Padding and border add to the total size.
div {
box-sizing: content-box;
width: 200px; /* content width */
padding: 20px; /* adds 40px total */
border: 2px solid; /* adds 4px total */
/* total width: 244px */
}
Width and height include content, padding, and border. This makes sizing much easier.
div {
box-sizing: border-box;
width: 200px; /* total width */
padding: 20px;
border: 2px solid;
/* content width: 156px */
}
box-sizing: border-box on all elements with the universal selector to simplify layout math:
*, *::before, *::after {
box-sizing: border-box;
}
When two vertical margins meet, the larger margin wins. They do not add together.
h1 { margin-bottom: 30px; }
h2 { margin-top: 20px; }
/* The gap between them is 30px, not 50px */
Create two <div> elements side by side. Set each to width: 50% with box-sizing: border-box and add padding and borders. Observe how border-box keeps them on the same line.