The Box Model is fundamental to CSS. Every element is a box with content, padding, border, and margin. Understanding it is crucial for layout and spacing.
Box Model Components
Every element consists of four layers, working from inside out:
Content: The actual content (text, images, etc.)
Padding: Space inside the border, around the content
/* Percentage of parent */
width: 50%;
height: 80%;
Maximum and Minimum Sizes
/* Don't grow larger than this */
max-width: 1200px;
/* Don't shrink smaller than this */
min-width: 300px;
/* Apply to height too */
max-height: 500px;
min-height: 200px;
Box-Sizing
Controls how width and height are calculated. Very important!
content-box (Default)
Width and height only include the content. Padding and border are added on top.
Width and height include content, padding, and border. Much more intuitive.
box-sizing: border-box;
/* Total width = 300px (padding and border included) */
width: 300px;
padding: 20px;
border: 2px solid;
/* Apply to all elements (best practice) */
* {
box-sizing: border-box;
}
Overflow
What happens when content is larger than the box:
overflow: visible; /* Content spills out (default) */
overflow: hidden; /* Content is cut off */
overflow: scroll; /* Scrollbars appear */
overflow: auto; /* Scrollbars only if needed (recommended) */
overflow: hidden - Content is cut off and hidden from view. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.
overflow: auto - Scrollbar appears because content overflows. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.