CSSbeginner 8 min
Understand content, padding, border and margin, the four layers around every element.
How every element is a box with content, padding, border and margin, and how to control each.
Almost every spacing problem ("why is there a gap here?") comes down to the box model. Once you see boxes, layout stops being mysterious.
Every element is a rectangle made of four layers, from inside to outside:
By default width only sets the content size, so padding and border make the box bigger. Add box-sizing: border-box; so that width includes padding and border. Most sites set it for everything.
* { box-sizing: border-box; } applies to every element so widths include padding and border..box is 200px wide in total, including its 20px padding and 4px border.background fills the content and padding, up to the border.margin: 20px leaves space outside the border. Adjacent vertical margins overlap, so the gap between the two boxes is 20px, not 40px.Increase padding to 40px and watch the content move away from the border. Then change margin to see the boxes move apart.
box-sizing: border-box and being surprised that the box is wider than width.text-align for text and margin: 0 auto for a block with a width.box-sizing: border-box so sizes are predictable.Next: laying elements out with flexbox.
.box {
padding: 16px;
border: 2px solid black;
margin: 24px;
}<style>
* {
box-sizing: border-box;
}
.box {
width: 200px;
padding: 20px;
border: 4px solid royalblue;
margin: 20px;
background: #e0e7ff;
}
</style>
<div class="box">Box one</div>
<div class="box">Box two</div>