Specifying cover
for background-size
makes the picture as small as possible while still covering the entire background area. contain
, on the other hand, makes the image as large as possible while not being clipped by the background area.
For an image with an intrinsic ratio, exactly one size matches the cover
/fit criteria alone. But if there is no intrinsic ratio specified, cover
/fit isn't sufficient, so the large/small constraints choose the resulting size.
Source: No dimensions or intrinsic ratio
If an image doesn't specify either dimensions or an intrinsic ratio, neither rule 2 nor rule 3 apply, so rule 4 takes over: the background image is rendered covering the entire background area. This satisfies the largest-or-smallest constraint.
background: url(no-dimensions-or-ratio.svg);
background-size: contain;
The rendered output looks like this:
Source: One specified dimension, no intrinsic ratio
Similarly, if the image has one dimension specified but no intrinsic ratio, rule 4 applies, and the image is scaled to cover the entire background area.
background: url(100px-wide-no-height-or-ratio.svg);
background-size: contain;
The rendered output looks like this:
Source: One specified dimension with intrinsic ratio
Things change when you specify an intrinsic ratio. In this case, rule 1 isn't relevant, so rule 2 is applied: we try to preserve any intrinsic ratio (while respecting contain
or cover
). For example, preserving a 3:4 intrinsic aspect ratio for a 300x200 box with contain
means drawing a 150x200 background.
contain case
background: url(100px-height-3x4-ratio.svg);
background-size: contain;
The rendered output looks like this:
Notice how the entire image is rendered, fitting as best as possible into the box without clipping any of it away.
cover case
background: url(100px-height-3x4-ratio.svg);
background-size: cover;
The rendered output looks like this:
Here, the 3:4 ratio is preserved while still stretching the image to fill the entire box. That causes the bottom of the image to be clipped away.
Source: No dimensions with intrinsic ratio
When using an image with no intrinsic dimensions but an intrinsic ratio, things work similarly.
contain case
background: url(no-dimensions-1x1-ratio.svg);
background-size: contain;
The rendered output looks like this:
Notice that the image is sized to fit the smallest dimension while preserving the 1:1 aspect ratio.
cover case
background: url(no-dimensions-1x1-ratio.svg);
background-size: cover;
The rendered output looks like this:
Here, the image is sized so that it fills the largest dimension. The 1:1 aspect ratio has been preserved, although with this source image, that can be difficult to see.