css - 如何拉伸背景图像以覆盖整个HTML元素?

我正在尝试获取HTML元素(body,div等)的背景图像以拉伸其整个宽度和高度。

没有太多运气。 除了作为背景图像之外,它是否可能或者我必须以其他方式做到这一点?

我目前的CSS是:

body {
background-position: left top;
background-image: url(_images/home.jpg);
background-repeat: no-repeat;
}

提前致谢。

编辑:我并不热衷于在Gabriel的建议中维护CSS,所以我改变了页面的布局。 但这似乎是最好的答案,所以我将其标记为这样。

10个解决方案

172 votes
{ margin: 0; padding: 0; }
html {
background: url('images/yourimage.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Nathan answered 2019-04-02T14:51:46Z
14 votes
使用background-size属性:[http://www.w3.org/TR/css3-background/#the-background-size]
Kornel answered 2019-04-02T14:52:11Z
8 votes

总之,你可以尝试这....



我用过少量css和js的地方......

它对我来说很好。

Tamal Samui answered 2019-04-02T14:53:07Z
6 votes

不确定是否可以拉伸背景图像。 如果您发现在所有目标浏览器中都不可能或不可靠,您可以尝试使用z-index设置为较低的拉伸img标记,并将位置设置为绝对,以便其他内容显示在其上。

让我们知道你最终做了什么。

编辑:我建议的基本上是加布里埃尔的链接。 所以尝试:)

Travis Collins answered 2019-04-02T14:54:01Z
4 votes
要扩展@PhiLho答案,您可以将一个非常大的图像(或任何大小的图像)居中在页面上:
{
background-image: url(_images/home.jpg);
background-repeat:no-repeat;
background-position:center;
}
或者您可以使用背景颜色与图像背景相匹配的较小图像(如果它是纯色)。 这可能适合您的目的,也可能不适合您。
{
background-color: green;
background-image: url(_images/home.jpg);
background-repeat:no-repeat;
background-position:center;
}
Traingamer answered 2019-04-02T14:54:39Z
4 votes
如果您需要在调整屏幕大小时拉伸背景图像,并且不需要与旧浏览器版本兼容,则可以执行以下操作:
body {
background-image: url('../images/image.jpg');
background-repeat: no-repeat;
background-size: cover;
}
leonardoborges answered 2019-04-02T14:55:23Z
3 votes
如果您有一个大的横向图像,此示例此处在纵向模式下调整背景大小,以便它显示在顶部,在底部留空:
html, body {
margin: 0;
padding: 0;
min-height: 100%;
}
body {
background-image: url('myimage.jpg');
background-position-x: center;
background-position-y: bottom;
background-repeat: no-repeat;
background-attachment: scroll;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
@media screen and (orientation:portrait) {
body {
background-position-y: top;
-webkit-background-size: contain;
-moz-background-size: contain;
-o-background-size: contain;
background-size: contain;
}
}
live-love answered 2019-04-02T14:55:56Z
3 votes
我主要使用以下代码来实现问题效果:
body {
background-image: url('../images/bg.jpg');
background-repeat: no-repeat;
background-size: 100%;
}
Badar answered 2019-04-02T14:56:23Z
2 votes
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
Behnam Mohammadi answered 2019-04-02T14:56:42Z
0 votes

你不能在纯CSS中。 在所有其他组件后面覆盖整个页面的图像可能是您最好的选择(看起来就像上面给出的解决方案)。 无论如何,无论如何,它看起来很糟糕。 我会尝试一个足够大的图像来覆盖大多数屏幕分辨率(比如高达1600x1200,高于稀疏度),限制页面的宽度,或者只是使用平铺图像。