CSS Max-width
CSS Max-width
The max-width property is used to limit how wide an element can grow. It is commonly used to create responsive layouts that adapt to different screen sizes.
Width vs Max-width
The width property sets a fixed width, while max-width sets an upper limit.
.box-width {
width: 800px;
}
.box-max {
max-width: 800px;
}
When the screen is smaller than 800px:
width: 800pxcauses horizontal scrollingmax-width: 800pxallows the element to shrink
Responsive Layouts with Max-width
Using max-width together with width: 100% is a common responsive pattern.
.container {
width: 100%;
max-width: 960px;
margin: auto;
}
This keeps content centered and readable on large screens while remaining flexible on small screens.
Images and Max-width
Images can overflow their containers if not constrained. Using max-width prevents this.
img {
max-width: 100%;
height: auto;
}
This ensures images scale down on smaller screens without distortion.
Max-width with box-sizing
When padding is added, box-sizing: border-box helps keep layouts predictable.
.content {
width: 100%;
max-width: 700px;
padding: 20px;
box-sizing: border-box;
}
Code Challenge
Goal: Create a responsive content container using max-width.
HTML:
<div class="content"> <h3>Responsive Layout</h3> <p>This container adapts to different screen sizes.</p> </div>
Task:
- Make the container full width on small screens
- Limit the maximum width on large screens
- Center the container horizontally
- Add padding without breaking the layout
Try a Solution:
.content {
width: 100%;
max-width: 720px;
margin: 40px auto;
padding: 20px;
box-sizing: border-box;
border: 1px solid #ddd;
border-radius: 12px;
}
What’s Next?
Next, you will learn how to position elements using CSS position properties.