CSS Max-width
Control maximum element width for responsive design
๐ What is Max-width?
The max-width property sets the maximum width of an element. It prevents the element from becoming wider than the specified value, making it essential for responsive design.
/* Basic max-width example */
.container {
max-width: 800px;
background-color: lightblue;
padding: 20px;
}
Output:
Max-width Values
Pixels (px)
Fixed maximum width in pixels
max-width: 500px;
Percentage (%)
Relative to parent element
max-width: 80%;
Viewport Units
Relative to viewport size
max-width: 90vw;
None
No maximum width limit
max-width: none;
๐น Responsive Container Example
Creating a responsive container that never exceeds 1200px but scales down on smaller screens uses max-width, percentage widths, and padding. CSS: .container { max-width: 1200px; width: 90%; margin: 0 auto; padding: 0 20px; }. The percentage width ensures fluidity on small viewports, while max-width caps expansion on large screens. Auto margins center the container. Adding box-sizing: border-box includes padding in width calculations. This pattern is foundational for responsive web design, providing consistent, readable line lengths and adapting gracefully across devices without media queries for basic behavior.
.responsive-container {
max-width: 1200px;
width: 100%;
margin: 0 auto;
padding: 20px;
background-color: #f0f8ff;
border: 2px solid #4169e1;
}
.content {
background-color: white;
padding: 15px;
border-radius: 5px;
}
Output:
๐น Max-width vs Width
Understanding max-width versus width is key to flexible, responsive layouts. width sets a fixed or percentage-based dimension; the element wonโt exceed it even if space is available. max-width sets a maximum limit but allows the element to shrink below that limit as needed. For responsive images, max-width: 100% ensures they scale down but never stretch beyond their intrinsic size. In containers, max-width with width: 100% creates fluid, bounded layouts. Using min-width together ensures elements remain usable across viewports, preventing awkwardly narrow or wide displays.
/* Fixed width - doesn't adapt */
.fixed-width {
width: 600px;
background-color: #ffcccb;
padding: 10px;
margin: 10px 0;
}
/* Max-width - adapts to smaller screens */
.flexible-width {
max-width: 600px;
width: 100%;
background-color: #90ee90;
padding: 10px;
margin: 10px 0;
}
Output:
๐น Practical Examples
Common use cases for max-width:
/* Image that doesn't exceed container */
.responsive-image {
max-width: 100%;
height: auto;
}
/* Card with maximum width */
.card {
max-width: 400px;
margin: 20px auto;
padding: 20px;
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
/* Text content with reading width */
.article-text {
max-width: 65ch; /* Optimal reading width */
line-height: 1.6;
margin: 0 auto;
}
Output:
Card Example
This card has a maximum width of 400px and will center itself. The text inside has an optimal reading width of 65 characters.