How can I keep a box within its parent while letting it shrink?
Quick answer
Give the box width: 100% and a max-width value, such as 40rem. The width lets it shrink to fit a narrower parent; the maximum stops it from growing wider than your chosen limit. In this combination, the box is as wide as the parent when that is smaller than the maximum, and no wider than the maximum otherwise. [S1]
The question, the details, the next step.
A practical checklist
Set
width: 100%so the box can use the parent’s available width.Choose a
max-widththat suits the layout; treat the example value as a placeholder.Check whether any
min-widthon the box takes precedence over the maximum.Compare how the box behaves with narrower and wider parents.
A few more useful answers
Does `max-width` make the box exactly the maximum width?
No. It sets an upper limit. With width: 100%, the box can be narrower when its parent has less available width. [S1]
What if `min-width` is larger than `max-width`?
The minimum takes precedence over the maximum. That can prevent the box from shrinking as much as the parent requires. [S1]
Sources
References used for this guide.
- [S1] The CSS max-width property developer.mozilla.org · Checked
