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

The quick brown fox jumps over the lazy dog. 素早い茶色の狐がのろまな犬を飛び越える。
Presets
Drag the bottom-right corner to resize

Code

.box {
  width: 100%;
  max-width: 320px;
}

Controls

max-width320px
The quick brown fox jumps over the lazy dog. 素早い茶色の狐がのろまな犬を飛び越える。

About

Writing the value

  • A length such as 320px, or 50%: never wider than that. Percentages are of the parent's width.
  • none: no upper limit. This is the initial value.
  • min-content, max-content and fit-content: use a width decided by the content as the limit. With max-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.

Comments