iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

CSS Max-width

max-width caps how wide an element is allowed to grow. Paired with width: 100%, it's the simplest responsive container pattern in CSS.

Why max-width beats fixed width

Wide viewport .container { max-width: 1100px } — capped, centred Narrow viewport (e.g. phone) shrinks to fit — never overflows Compare with width: 1100px → forces a horizontal scrollbar on phones.
Fig 1. max-width is a ceiling. On smaller screens the element just shrinks.

The responsive container recipe

CSS
.container {
  width: 100%;
  max-width: 1100px;
  margin-left: auto;
  margin-right: auto;
  padding-left: 20px;
  padding-right: 20px;
}
Tip: Use the same pattern for media: img, video { max-width: 100%; height: auto; } stops anything overflowing its parent.

Example

Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>

<h1>CSS Max-width</h1>
<div class="box">Edit the CSS on the left, then click Run &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Make this image responsive while keeping its aspect ratio.

img { max-width: 100%; height: ; }

Test yourself

Q1. What is the advantage of `max-width` over a fixed `width`?
Q2. Which is the canonical responsive-image one-liner?
Q3. A centred page container usually combines `max-width` with…

Discussion

Loading…