width
Example
.container {
width: 1200px;
margin-inline: auto;
}.container {
width: min(100% - 2rem, 1200px);
margin-inline: auto;
}min() caps the width at '1200px' but shrinks it on small screens, keeping a side gutter.
Common mistakes
- A fixed
widthin pixels overflows on small screens. width: 100%plus padding makes the element wider than its parent.
Key points
- Layout containers use
max-widthormin()instead of a fixed pixelwidth. - Elements with
width: 100%and padding usebox-sizing: border-box. - Full-width sections use '100%', not '100vw', to avoid horizontal scrolling.
Interview questions
What is the default width of a block element?
'auto', which fills the containing block's width minus margins, border and padding.
What is the difference between width: auto and width: 100%?
'auto' fits the available space including margins, while '100%' sets the content box to the parent width and can overflow with padding or margins.
Does width work on inline elements?
No. width is ignored on non-replaced inline elements like span; use 'inline-block' or another display value.