CSS Min and Max Size

The min and max size properties set boundaries so an element never shrinks below or grows beyond a chosen limit.

Fixed widths and heights are rigid, which can break layouts on different screen sizes. The min and max properties let an element flex within a safe range, which is a cornerstone of responsive design.

The four properties

PropertyEffect
min-widthElement will not become narrower than this
max-widthElement will not become wider than this
min-heightElement will not become shorter than this
max-heightElement will not become taller than this

Responsive images

<!DOCTYPE html>
<html>
<head>
<style>
img {
  max-width: 100%;
  height: auto;
}
</style>
</head>
<body>

<img src="photo.jpg" alt="Mountain view">

</body>
</html>

Setting <max-width> to 100% on an image is one of the most common responsive rules. It lets the image shrink to fit narrow screens while never stretching past its natural size, and height: auto keeps its proportions.

Constraining a text column

Readable, flexible container

<!DOCTYPE html>
<html>
<head>
<style>
.article {
  width: 100%;
  max-width: 720px;
  min-width: 320px;
  margin: 0 auto;
}
</style>
</head>
<body>

<div class="article">
  <p>This column stays readable at any screen width.</p>
</div>

</body>
</html>
Note: When both width and max-width are set, max-width always wins if there is a conflict. The same is true for min-width, which takes priority over both.

Exercise: CSS Height / Width

With the default `box-sizing: content-box`, does the `width` property include padding and border?