The CSS max-width property sets the maximum width an element can reach. It prevents block elements from stretching too wide on desktop screens while allowing them to shrink fluidly on mobile screens.
width: 100% vs max-width: 600pxUsing max-width is superior to hardcoding width: 600px for responsive web design:
/* Fixed Width (Breaks on mobile screens smaller than 600px) */
.fixed-box {
width: 600px;
}
/* Responsive Max-Width (Scales fluidly on mobile) */
.responsive-box {
width: 100%;
max-width: 600px;
margin: 0 auto;
}
Key benefits of max-width:
600px, max-width shrinks the box to fit 100% of the viewport.margin: 0 auto; to create clean, centered desktop layouts.flowchart TD
A["Browser Viewport Resizing"] --> B{"Screen Width > 600px?"}
B -- Yes --> C["Box caps at 600px (Centered via margin: auto)"]
B -- No --> D["Box contracts fluidly to 100% of mobile screen width"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Max-Width Demonstration</title>
<style>
.container {
width: 100%;
max-width: 750px;
margin: 2rem auto;
background-color: #1e293b;
padding: 2rem;
border-radius: 8px;
}
</style>
</head>
<body style="background-color: #0f172a; color: #f8fafc; font-family: system-ui, sans-serif; padding: 1rem;">
<div class="container">
<h2 style="color: #38bdf8;">Responsive Max-Width Container</h2>
<p>Resize your browser window to watch this box shrink cleanly on small screens without creating horizontal scrollbars!</p>
</div>
</body>
</html>
max-width with width: 100%: Guarantees elements contract smoothly on small mobile viewports.max-width: 100% on images: Ensures large uploaded image assets scale down inside small card wrappers.max-width: 65ch or 700px on article text to optimize reading comfortable line lengths.Create a CSS class .article-wrapper configured with width: 100%, max-width: 700px, and margin: 0 auto!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.