html - 背景大小之间的差异 :cover and background-size:contain

标签 html css background

在视觉上我可以体会到差异,但在哪些情况下我应该更喜欢其中一种呢? 使用它们有什么意义,还是可以用百分比代替?

目前,在使用这些属性时,我似乎无法超越试错法,这让我很头疼。

我也只能找到非常模糊的解释,尤其是我找到了 W3C doc非常莫名其妙。

Values have the following meanings:

‘contain’

Scale the image, while preserving its intrinsic aspect ratio (if any), to the largest size such that both its width and its height can fit inside the background positioning area.

‘cover’

Scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area.

我可能有点厚,但是谁能给我一个通俗易懂的英文解释和相关的例子?

请使用this fiddle .谢谢。

CSS

body{
    width:500px;
    height:500px;
    background:url(http://upload.wikimedia.org/wikipedia/commons/1/1a/Bachalpseeflowers.jpg);
    background-size:contain;
    background-repeat:no-repeat;
}

注意

接受的答案是我目前认为最简洁和完整的答案。 感谢大家的帮助。

最佳答案

您可以考虑查看控制输出的伪代码。分配给图像大小的值直接取决于容器的宽高比与背景图像的宽高比。

注意: 宽高比=宽/高

包含

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

封面

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

你看到关系了吗?在 covercontain 中,纵横比都保持不变。但是 if - else 条件在这两种情况下都相反。

这就是使 cover 覆盖整个页面的原因,没有任何白色部分可见。当容器的纵横比较大时,缩放图像使其宽度等于容器宽度。现在,高度会更大,因为纵横比更小。因此它覆盖了整个页面,没有任何白色部分。

问。可以用百分比代替吗?

不,不仅仅是百分比。你需要调理。

问。在哪些情况下我应该更喜欢其中一种?

当您创建网站时,您不希望固定背景中有任何白色部分。所以使用cover

contain 另一方面可以在您使用重复背景时使用(例如,当您的图案图像具有非常高的纵横比 wrt veiwport/container 时,您可以使用 contain 并将 background-repeat 设置为 repeat-y)。但是 contain 更合适的用途是用于固定高度/宽度的元素。

关于html - 背景大小之间的差异 :cover and background-size:contain,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27939971/

相关文章:

javascript - 带有内联 svg 的 CSS 背景

php - 我可以动态附加 og 标签并渲染它吗?

html - 让一封信延伸到页面下方?

css - Laravel SASS - 自定义输入目录

css - 动画背景大小在最新版本的 Chrome 中无法正常运行

html - 火狐错误?在 img 上得到不需要的(和未编码的)笔划(在其他浏览器上工作)

javascript - 如何使用 JavaScript 悬停事件更改特定元素的 CSS(BG 颜色)?

html - 限制显示 Sprite 表作为文本框背景

jquery - 砌体,不调整高度,只调整宽度

javascript - 多部分/表单数据可以用 javascript 发送吗?