CSS Max-width

max-width caps how wide an element can grow while still letting it shrink on small screens, making it the backbone of readable, centered layouts.

A fixed width forces an element to one exact size, which overflows narrow screens. max-width instead sets an upper limit: the element can be any width up to that cap, but is free to become narrower when there is less room.

width versus max-width

PropertyOn a wide screenOn a narrow screen
width: 800pxExactly 800pxStill 800px, causing overflow
max-width: 800pxUp to 800pxShrinks to fit the screen

A responsive width cap

<!DOCTYPE html>
<html>
<head>
<style>
.content {
  max-width: 800px;
  width: 100%;
}
</style>
</head>
<body>

<div class="content">
  <p>This paragraph never grows wider than 800px.</p>
</div>

</body>
</html>

Centering with auto margins

Pairing max-width with margin: 0 auto is the classic way to build a centered page container. Once the element is narrower than its parent, the automatic left and right margins split the leftover space evenly.

Centered container

<!DOCTYPE html>
<html>
<head>
<style>
.container {
  max-width: 960px;
  margin: 0 auto;
  padding: 0 16px;
}
</style>
</head>
<body>

<div class="container">
  <h1>Page title</h1>
  <p>The container centers this content.</p>
</div>

</body>
</html>

Keeping images in bounds

A very common use is max-width: 100% on images, which stops a large image from spilling past its container while still allowing it to scale down.

Fluid images

<!DOCTYPE html>
<html>
<head>
<style>
img {
  max-width: 100%;
  height: auto;
}
</style>
</head>
<body>

<img src="mountain.jpg" alt="Mountain landscape">

</body>
</html>
Note: Add side padding to your container as well. Without it, text can touch the very edge of the screen on phones even when max-width is set.

Exercise: CSS Max-width

What does max-width do when content would otherwise make an element wider than that value?