CSS Min/Max Height and Width
Four properties put limits on an element's size. Width is bounded by min-width (smallest) and max-width (largest), and height by min-height (smallest) and max-height (largest) in the same way.
CSS Using max-width
With max-width, you cap how wide an element may get: it will not grow past the value you give.
Accepted values:
- a length — the cap in
px,cm, and so on. - a percent — the cap relative to the containing block.
none— no cap at all, which is the default.
Plain width causes trouble in a browser window smaller than the element, since a horizontal scrollbar appears. max-width copes better with small windows.
CSS max-width Examples
The two divs behave differently once the browser window is narrower than 500px, so try shrinking it.
Note: When an element has both width and max-width and the width is the larger one, max-width takes effect.
max-width vs width
A narrow window makes the max-width div shrink to fit. The fixed width div stays as it is.
<style> block, make a .div1 class with max-width 500px and a powderblue background, and a .div2 class with width 500px and a powderblue background. Add a div of each class with text. On a narrow window, the max-width div shrinks while the fixed-width div keeps its size.
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.div1 {
max-width: 500px;
background-color: powderblue;
}
.div2 {
width: 500px;
background-color: powderblue;
}
</style>
</head>
<body>
<div class="div1">This element has a max-width of 500 pixels.</div>
<br>
<div class="div2">This element has a width of 500 pixels.</div>
</body>
</html>
width and max-width together
At 100% width the div fills its container, up to a limit of 900px.
<style> block, give a .div1 class width 100% and max-width 900px, with a powderblue background. The element grows to fill its container but never wider than 900px. Add a div with text.
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.div1 {
width: 100%;
max-width: 900px;
background-color: powderblue;
}
</style>
</head>
<body>
<div class="div1">This element has a width of 100% but never grows wider than 900px.</div>
</body>
</html>
All CSS Dimension Properties
Dimension properties at a glance:
height— how tall an element is.max-height— the largest allowed height.max-width— the largest allowed width.min-height— the smallest allowed height.min-width— the smallest allowed width.width— how wide an element is.