Box
max-width
max-width sets an upper limit on the width of an element. Even a box that stretches with its parent, like width: 100%, never gets wider than max-width. It is a staple of layouts that adapt to the screen width.
Syntax
none | <length-percentage [0,∞]> | min-content | max-content | fit-content | fit-content(<length-percentage [0,∞]>)Preview
Code
.box {
width: 100%;
max-width: 320px;
}Controls
About
Writing the value
- A length such as
320px, or50%: never wider than that. Percentages are of the parent's width. none: no upper limit. This is the initial value.min-content,max-contentandfit-content: use a width decided by the content as the limit. Withmax-content, the box never gets wider than its text laid out without wrapping.
A common pairing
The preview on this page adds max-width to a box with width: 100%. When the parent is wide, the box stops at max-width; when it is narrow, the box shrinks with the parent. Dragging the handle at the bottom right of the preview box also stops at max-width.
To keep lines of text from getting too long, use a unit based on the font size such as 40em, so the number of characters per line stays the same when the text gets bigger. Giving images max-width: 100% keeps images larger than their parent within its width.
When it conflicts with min-width, min-width wins.