The relationship and effect of width: 100%
used with max-width
depends on the context that it's used with. The default value of block-level elements is width: 100%
, therefore that declaration is redundant unless it is overruling another inherited value.
A possible scenario could involve replaced elements, such as images. The default width is its intrinsic value (even if given display: block
). To give an image a responsive fit and keep its intrinsic aspect ratio, give it width: 100%
(height: auto
is the default and wouldn't need to be declared unless overruling another inherited value.)
This allows the image to shrink to fit, but it will also increase its size to fit. To prevent the image from exceeding a specific (possibly intrinsic) size, declare max-width
.
Using this example:
- parent element
width: 500px
and not responsive
- child element
width: 100%
and max-width: 300px
The child element will either reduce or increase its width and is equivalent to having used width: 300px
. It will always be 300px wide.
However, if the parent element is responsive (such as a flexbox item), then the child element will be responsive and can shrink below 300px while keeping its aspect ratio. This is demonstrated in the snippet.
section {
display: flex;
background-color: aliceblue;
}
div {
width: 500px;
}
img {
display: block;
width: 100%;
max-width: 300px;
margin: auto;
}
p {
padding: 1em;
}
<section>
<div>
<img src="//picsum.photos/400" alt="placeholder photo">
</div>
<p>The randomly-generated placeholder photo has an intrinsic size of 400px by 400px. However, its rendered size is limited to 300px and is allowed to shrink in narrow viewports.</p>
</section>