You can consider looking at the pseudocodes that govern the output. The values allotted to the image's size depend directly on the aspect ratios of container wrt aspect ratio of the background image.
Note: Aspect ratio = width / height
Contain
if (aspect ratio of container > aspect ratio of image)
image-height = container-height
image-width = aspect-ratio-preserved width
else
image-width = container width
image-height = aspect-ratio-preserved height
Cover
if (aspect ratio of container > aspect ratio of image)
image-width = container width
image-height = aspect-ratio-preserved height
else
image-height = container height
image-width = aspect-ratio-preserved width
You see the relation? In both cover
and contain
, aspect ratio is preserved. But the if - else conditions reverse in both the cases.
This is what makes cover
to cover full page, without any white portion visible. When aspect ratio of container is greater, scaling image so that its width becomes equal to container width. Now, height will be greater, as aspect ratio is smaller. Thus it covers the whole page without any white portion.
Q. Can they be replaced by percentages?
No, not simply by percentages. You'll need conditioning.
Q. In which situations should I prefer one over the other?
When you are creating a website, you wouldn't want any white portion in the fixed background. So use cover
.
contain
on the other can be used when you are using a repeating background (e.g. when you have a pattern image with very high aspect ratio wrt veiwport/container you can use contain
and set background-repeat
to repeat-y
). But a more appropriate use for contain
would be for a fixed height/width element.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…