Lesson

CSS Max-width

10 min reading
Free Course

CSS Max-Width: Responsive Containers Without Overflow

Using CSS max-width instead of a rigid width lets a container stretch comfortably on wide screens while shrinking automatically to fit narrow smartphones. Combining max-width with margin-inline: auto; is the simplest way to build centered, responsive page layouts.

Why width Alone Breaks on Mobile

Suppose you build a centered article wrapper with width: 900px; margin: 0 auto;. On a 1440px laptop it looks crisp—but on a 375px phone, the fixed 900px box overflows off the right edge and forces awkward horizontal scrolling.

Replacing width: 900px with width: 100%; max-width: 900px; solves this in one line: on phones the box occupies 100% of the screen cleanly, and on desktops it caps neatly at 900px.

.page-wrapper {
    width: 100%;
    max-width: 1080px;
    margin-inline: auto;
    padding-inline: 16px;
}

.readable-prose {
    max-width: 65ch;
    line-height: 1.65;
}

.responsive-media {
    display: block;
    max-width: 100%;
    height: auto;
}

Using ch Units for Comfortable Reading

Setting max-width: 65ch; on blog articles caps line width at roughly 65 characters of the active font, matching classic typography rules regardless of whether the user views the page at 16px or 20px font size.

Common Mistakes to Avoid

  • Setting max-width without padding-inline on mobile: When a 100% container hits phone edges, text touches the glass bezel unless you add 16px horizontal padding.
  • Stretching tiny raster images with width: 100% instead of max-width: 100%: max-width: 100% scales large images down to fit containers without pixelating small icons upward.
  • Forgetting box-sizing: border-box with width: 100% and padding: Without border-box, adding padding-inline: 16px pushes width: 100% past the right edge.

Frequently Asked Questions

What happens if both width and max-width are set on the same element?

max-width always wins when the computed width exceeds max-width. For instance, width: 100%; max-width: 600px; stops growing at 600px.

Does CSS also have min-width?

Yes. min-width ensures an element—such as a button or grid column—never shrinks narrower than a minimum readable threshold.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
CSS Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum