我有
body {
background: url(images/background.svg);
}
期望的效果是此背景图像的宽度与页面的宽度相等,高度会发生变化以保持比例。例如,如果原始图像恰好为 100*200(任何单位)并且正文为 600px 宽,则背景图像最终应为 1200px 高。如果调整窗口大小,高度应自动更改。这可能吗?
目前,Firefox 看起来像是先调整高度再调整宽度。这可能是因为高度是最长的尺寸并且它试图避免裁剪?我 想 垂直裁剪,然后滚动:没有水平重复。
此外,Chrome 将图像放在中心,不再重复,即使明确给出了 background-repeat:repeat
,这是默认设置。
原文由 spraff 发布,翻译遵循 CC BY-SA 4.0 许可协议
为此有一个 CSS3 属性,即
background-size
( 兼容性检查)。虽然可以设置长度值,但它通常与特殊值contain
和cover
使用。在您的具体情况下,您应该使用cover
:contain
和cover
的卵子移植抱歉,双关语不好,但我将使用 Biswarup Ganguly 的今日图片 进行演示。假设这是您的屏幕,灰色区域在您可见的屏幕之外。为了演示,我将假设一个 16x9 的比例。
我们想使用上述当天的图片作为背景。但是,出于某种原因,我们将图像裁剪为 4x3。我们可以将
background-size
属性设置为某个固定长度,但我们将关注contain
和cover
。请注意,我还假设我们没有body
的宽度和/或高度。contain
div > div { margin: 0 1ex 1ex 0; float: left; } div + div { clear: both; border-top: 1px dashed silver; padding-top:1ex; } div > div::after { background-color: #000; color: #fefefe; margin: 1ex; padding: 1ex; opacity: 0.8; display: block; width: 10ex; font-size: 0.7em; content: attr(class); }
Note the grey background. The image does not cover the whole region, but it’s fully contained.
Note the ducks/geese at the bottom of the image. Most of the water is cut, as well as a part of the sky. You don’t see the complete image anymore, but neither do you see any background color; the image covers all of the
<div>
.