CSS Tutorial
CSS Max-width
The max-width property sets an upper limit on how wide an element can grow. It is the key to responsive containers that stay readable on big screens but shrink gracefully on small ones.
The max-width property
A block element with a fixed width can overflow small screens, while an element with no width limit can stretch uncomfortably wide on large monitors. max-width solves both problems: the element uses its natural or set width up to the limit, and never grows beyond it, but it is still free to shrink on narrow screens.
width vs max-width
| Property | Effect |
|---|---|
| width: 600px | Always exactly 600px, even if the screen is only 400px wide (overflow) |
| max-width: 600px | Up to 600px, but shrinks to fit smaller screens |
| min-width: 300px | Never narrower than 300px |
Compare the two boxes below on a narrow viewport. The fixed-width box can spill out of the frame, while the max-width box adapts.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: system-ui, sans-serif; padding: 16px; }
.fixed {
width: 500px;
background: #fecaca;
padding: 12px;
margin-bottom: 12px;
}
.fluid {
max-width: 500px;
background: #bbf7d0;
padding: 12px;
}
</style>
</head>
<body>
<div class="fixed">width: 500px — can overflow a small screen.</div>
<div class="fluid">max-width: 500px — shrinks to fit smaller screens.</div>
</body>
</html>Centring a responsive container
The most common use of max-width is a page container. Combine max-width with margin: auto to centre a block horizontally, and it will stay centred and readable at every screen size.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: system-ui, sans-serif; background: #e2e8f0; margin: 0; }
.container {
max-width: 400px;
margin: 20px auto; /* auto left/right = centred */
background: white;
padding: 20px;
border-radius: 10px;
}
</style>
</head>
<body>
<div class="container">
<h3>Readable column</h3>
<p>This box is centred and never grows wider than 400px, so text stays comfortable to read.</p>
</div>
</body>
</html>For images, max-width: 100% together with height: auto is the classic trick to make pictures scale down inside their container without distortion.
Key points
- max-width caps how wide an element can grow but still lets it shrink.
- Prefer max-width over a fixed width for responsive, overflow-free layouts.
- max-width plus margin: auto centres a block container horizontally.
- img { max-width: 100%; height: auto; } keeps images inside their box.
