The CSS max-width Property
The max-width property sets the largest width an element can have. The element can be narrower than this value, but never wider.
It is useful for responsive layouts and for keeping content readable across different screen sizes.
Problem with width: A centered <div> with a fixed width, such as 600px, will overflow when the browser window is narrower than that width, and the browser may add a horizontal scrollbar.
Using max-width instead: Setting max-width handles small windows better, because the element shrinks to fit instead of overflowing.
Example
One div uses a fixed width and the other uses max-width, so only the second one shrinks on a narrow window.
Prompt
An HTML page comparing a fixed width with max-width on two centered divs.
In an internal
<style> block, make div.ex1 with width 500px, margin auto, and a 3px solid green border; and div.ex2 with max-width 500px, margin auto, and the same border. Add a div of each class with text. On a narrow window, the fixed-width div overflows while the max-width div shrinks.
Output: complete HTML page
index.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
div.ex1 {
width: 500px;
margin: auto;
border: 3px solid #73AD21;
}
div.ex2 {
max-width: 500px;
margin: auto;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<div class="ex1">This div has a width of 500px and margin set to auto.</div>
<br>
<div class="ex2">This div has a max-width of 500px and margin set to auto.</div>
<p>Resize the browser window to less than 500px wide to see the difference.</p>
</body>
</html>
CSS Properties
A summary of the properties here:
max-width— sets the maximum width of an element.width— sets the width of an element.