CSS背景图片以适应宽度,高度应按比例自动缩放

新手上路,请多包涵

我有

body {
    background: url(images/background.svg);
}

期望的效果是此背景图像的宽度与页面的宽度相等,高度会发生变化以保持比例。例如,如果原始图像恰好为 100*200(任何单位)并且正文为 600px 宽,则背景图像最终应为 1200px 高。如果调整窗口大小,高度应自动更改。这可能吗?

目前,Firefox 看起来像是先调整高度再调整宽度。这可能是因为高度是最长的尺寸并且它试图避免裁剪?我 垂直裁剪,然后滚动:没有水平重复。

此外,Chrome 将图像放在中心,不再重复,即使明确给出了 background-repeat:repeat ,这是默认设置。

原文由 spraff 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 898
2 个回答

为此有一个 CSS3 属性,即 background-size兼容性检查)。虽然可以设置长度值,但它通常与特殊值 containcover 使用。在您的具体情况下,您应该使用 cover

 body {
    background-image:    url(images/background.svg);
    background-size:     cover;                      /* <------ */
    background-repeat:   no-repeat;
    background-position: center center;              /* optional, center the image */
}

containcover 的卵子移植

抱歉,双关语不好,但我将使用 Biswarup Ganguly 的今日图片 进行演示。假设这是您的屏幕,灰色区域在您可见的屏幕之外。为了演示,我将假设一个 16x9 的比例。

屏幕

我们想使用上述当天的图片作为背景。但是,出于某种原因,我们将图像裁剪为 4x3。我们可以将 background-size 属性设置为某个固定长度,但我们将关注 containcover 。请注意,我还假设我们没有 body 的宽度和/或高度。

contain

>  contain
>
> ```
>
> 将图像缩放到最大尺寸,同时保留其固有的纵横比(如果有),使其宽度和高度都能适应背景定位区域。

这可以确保背景图像始终完全包含在背景定位区域中,但是,在这种情况下,可能会有一些空白空间填充您的 `background-color` :

![包含](https://i.stack.imgur.com/mAtCl.png)

### `cover`

> ```
>  cover
>
> ```
>
> 缩放图像,同时保留其固有的纵横比(如果有)到最小尺寸,使其宽度和高度都可以完全覆盖背景定位区域。

这样可以确保背景图像覆盖所有内容。将没有可见的 `background-color` ,但是根据屏幕的比例,您的图像的很大一部分可能会被切断:

![覆盖](https://i.stack.imgur.com/p96P5.png)

### 实际代码演示

div > div { background-image: url(http://i.stack.imgur.com/r5CAq.jpg); background-repeat: no-repeat; background-position: center center; background-color: #ccc; border: 1px solid; width: 20em; height: 10em; } div.contain { background-size: contain; } div.cover { background-size: cover; } /******************************************** Additional styles for the explanation boxes *********************************************/

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 &lt;div&gt;.

“`

原文由 Zeta 发布,翻译遵循 CC BY-SA 3.0 许可协议

根据 https://developer.mozilla.org/en-US/docs/CSS/background-size 的提示,我最终得到了以下对我有用的方法

body {
        overflow-y: hidden ! important;
        overflow-x: hidden ! important;
        background-color: #f8f8f8;
        background-image: url('index.png');
        /*background-size: cover;*/
        background-size: contain;
        background-repeat: no-repeat;
        background-position: right;
}

原文由 Yauhen Yakimovich 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏