CSS
What’s the Difference Between max-width and width in CSS?
When styling web pages, choosing between width
and max-width
can significantly impact how your layout behaves across screen sizes. Though they seem similar, these two CSS properties serve different purposes—and understanding their difference is crucial for building responsive designs.
In this blog post, we’ll explore:
- The purpose of each property
- Key differences
- Practical examples
- When to use
width
, when to usemax-width
🎯 What Is width
?
The width
property sets the exact horizontal size of an element.
.box {
width: 600px;
}
✅ Result: The box will always be 600 pixels wide, no matter the screen size or parent container.
📐 What Is max-width
?
The max-width
property sets the maximum allowed width of an element. The element can shrink below this value—but won’t grow beyond it.
.box {
max-width: 600px;
}
✅ Result: The box will be as wide as its content or container, but never exceed 600px.
🆚 Key Differences Between width
and max-width
Feature | width | max-width |
---|---|---|
Fixed size? | Yes | No |
Responsive? | Less flexible | More responsive-friendly |
Can shrink below? | No | Yes |
Can exceed limit? | N/A | No — capped at max-width |
🧪 Real-World Example
Using width
:
.container {
width: 960px;
}
🛑 On small screens, this may overflow the viewport and break your layout.
Using max-width
:
.container {
width: 100%;
max-width: 960px;
margin: 0 auto;
}
✅ On small screens, the container scales down.
✅ On large screens, it doesn’t exceed 960px.
✅ It’s centered using margin: 0 auto
.
This pattern is ideal for responsive layouts.
💡 When to Use Each
Use Case | Best Option |
---|---|
Fixed-width component | width |
Responsive page layout | max-width |
Preventing overflow on large screens | max-width |
Keeping form fields aligned | Combine both (width: 100%; max-width: 400px; ) |
📝 Conclusion
While width
locks an element to a specific size, max-width
gives it the flexibility to adapt to different screen sizes—making it ideal for modern, mobile-first web design.
For most responsive designs, use:
width: 100%;
max-width: [your limit];
This approach ensures content scales fluidly, while staying readable and contained.
🔑 Recap
Property | Controls… | Best For… |
---|---|---|
width | Fixed size | Static, precise layouts |
max-width | Max flexibility | Responsive, fluid layouts |