Learn the concept
The CSS Box Model
Every element is a rectangular box with four layers: content (the actual text/image), padding (space between content and border), border (the visible edge), and margin (space outside the border). By default, width/height set only the content size; use box-sizing: border-box to include padding and border.
The CSS box model defines how every HTML element is rendered as a rectangular box.
The four layers (inside out):
box-sizing property:
content-box (default): width = content only. Total width = width + padding + borderborder-box: width = content + padding + border. Much more intuitive!Margin collapsing:
Best practices:
box-sizing: border-box globally — it's what every modern CSS reset and framework does.margin-block, padding-inline) for styles that adapt to international writing modes./* Global reset — every modern project does this */
*, *::before, *::after {
box-sizing: border-box;
}
/* content-box (default) */
.content-box {
box-sizing: content-box;
width: 200px;
padding: 20px;
border: 5px solid black;
/* Total width: 200 + 20*2 + 5*2 = 250px */
}
/* border-box (recommended) */
.border-box {
box-sizing: border-box;
width: 200px;
padding: 20px;
border: 5px solid black;
/* Total width: 200px (content shrinks to 150px) */
}Where each card needs consistent padding and border, and you want its overall width to be predictable regardless of these internal spaces.
Where menu items have internal padding but you want their total width to respect a parent container's layout without overflow.
That needs precise control over its dimensions, including padding and borders, to fit perfectly within the viewport.
A gallery of images that adapts to different screen sizes and uses the box model for consistent spacing and sizing of image containers.
Design and implement custom buttons with interactive hover effects, utilizing the box model to manage their dimensions and internal spacing.
GitHub uses the box model extensively for layout and component sizing across its interface. For instance, user profile cards, code blocks, and navigation elements all leverage `box-sizing: border-box` to maintain consistent dimensions and spacing.
Stripe's dashboard and payment forms rely on a well-defined box model to ensure that input fields, buttons, and informational cards are rendered consistently across different browsers and devices, providing a polished user experience.