Box Model and Sizing
Understand content boxes, padding, borders, margins, box sizing, dimensions, overflow, and intrinsic sizing.
The CSS Box Model
Every normal CSS box consists conceptually of content, padding, border, and margin. With the default content-box sizing model, declared width applies to the content area only. Padding and borders are then added to the rendered dimensions.
This is why many projects use box-sizing: border-box, which makes declared width and height include padding and borders.
*,
*::before,
*::after {
box-sizing: border-box;
}
.card {
width: 300px;
padding: 20px;
border: 4px solid #334155;
}border-box, the total outer width remains 300px instead of becoming 348px.- The box model consists of content, padding, border, and margin.
border-boxmakes sizing easier to reason about.
With `box-sizing: border-box`, what does the declared width include?
Width and Height
CSS supports fixed dimensions such as px, relative dimensions such as %, viewport units such as vw and vh, and intrinsic keywords such as auto, min-content, max-content, and fit-content.
Avoid forcing fixed heights on content-heavy components unless the design genuinely requires them. Content can vary due to localization, user settings, and responsive layouts.
.container {
width: min(100% - 2rem, 1200px);
min-height: 100dvh;
}
.card {
width: min(100%, 420px);
min-height: 200px;
}min() allow CSS to express responsive constraints without many media queries.- Prefer intrinsic and fluid sizing where appropriate.
- Use fixed dimensions only when the component genuinely needs fixed geometry.
Which function is useful for selecting the smaller of multiple sizing constraints?
Margin, Padding and Border
Padding creates space between content and the border. Margin creates space outside the border. Borders visually surround the padding and content areas.
Logical properties such as margin-inline, padding-block, and border-inline-start are preferable when building interfaces that may support different writing directions.
.panel {
padding-block: 1.5rem;
padding-inline: 2rem;
margin-inline: auto;
border-inline-start: 4px solid currentColor;
}- Padding is inside the border; margin is outside.
- Logical properties improve internationalization support.
Which property creates space inside an element's border?
Overflow and Clipping
Overflow occurs when content exceeds the available box. The overflow, overflow-x, and overflow-y properties control whether overflowing content is visible, clipped, or scrollable.
overflow: hidden is sometimes useful, but blindly hiding overflow can make content inaccessible. For scrollable regions, consider keyboard access and visible scroll affordances.
.code-panel {
max-height: 400px;
overflow: auto;
overscroll-behavior: contain;
}- Use overflow intentionally.
- Avoid hiding content that users need to access.
Which value allows scrolling when content overflows?