Difference between background-size:cover and background-size:contain

前端 未结 6 633
孤独总比滥情好
孤独总比滥情好 2020-12-08 02:38

Visually I can appreciate the difference, but in which situations should I prefer one over the other? Is there any point using them at all or can they be replaced by percent

6条回答
  •  盖世英雄少女心
    2020-12-08 03:15

    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.

提交回复
热议问题