CSS:全尺寸背景图像

CSS:全尺寸背景图像,css,Css,正在尝试使用以下内容获取全尺寸背景图像: html { height: 100%; background:url('../img/bg.jpg') no-repeat center center fixed; background-size: cover; } 它以正确的宽度显示背景图像,但高度被拉伸。 我尝试了各种选择,比如 html { background:url('../img/bg.jpg') no-repeat center center fixed; ba

正在尝试使用以下内容获取全尺寸背景图像:

html {
    height: 100%;
    background:url('../img/bg.jpg') no-repeat center center fixed;
    background-size: cover;
}
它以正确的宽度显示背景图像,但高度被拉伸。 我尝试了各种选择,比如

html {
background:url('../img/bg.jpg') no-repeat center center fixed;
background-size: 100% auto;
-webkit-background-size: 100% auto;
-moz-background-size: 100% auto;
-o-background-size: 100% auto;
}

移除高度:100%


但它们都不起作用。

尝试使用contain代替cover,然后将其居中:

background-size: contain;
background-position: center;

您的屏幕显然与图像的形状不同。这并不罕见,即使你的屏幕是相同的形状(纵横比),你也应该始终适应这种情况,因为其他人的屏幕并不总是相同的。要解决此问题,您只有以下三种选择之一:

  • 您可以选择用图像完全覆盖屏幕,但不要扭曲图像。在这种情况下,您将需要处理这样一个事实,即图像的边缘将被切断。对于这种情况,请使用:
    背景尺寸:封面
  • 您可以选择确保整个图像可见,且不失真。在这种情况下,您需要考虑到这样一个事实,即一些背景不会被您的图像覆盖。处理这一问题的最佳方法是给页面提供一个坚实的背景,并将图像设计为淡入坚实的背景(尽管这并不总是可能的)。对于这种情况,请使用:
    background size:contain
  • 您可以选择用背景覆盖整个屏幕,并对其进行扭曲以适应。对于这种情况,请使用:
    背景大小:100%100%

更好的解决方案可能是使用轻量级jQuery插件动态调整浏览器站点的背景大小。我最喜欢的是backstretch.js。它们的实现非常简单。

您应该使用主体作为选择器,而不是html,这将导致标记出现问题。您的代码如下:

html {
    height: 100%;
    background:url('../img/bg.jpg') no-repeat center center fixed;
    background-size: cover;
}
我想尝试一下:

body {
    background:url('../img/bg.jpg') no-repeat 50% 0 fixed;
    margin: 0 auto;
}

您不必为图像指定尺寸

我有同样的问题,我在
主体上使用这个CSS

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;
background: url(image.jpg);
    background-color: rgba(0, 0, 0, 0);
    background-position-x: 0%;
    background-position-y: 0%;
    background-size: auto auto;
background-color: #0a769d;
height: 100%;
min-height: 100%;
max-height: 100%;
width: 100%;
background-size: 100% 100%;
background-position: center;
max-width: 100%;
min-width: 100%;
top: 0;
left: 0;
padding: 0;
margin: 0;

当你说拉伸时,你的意思是图像的形状被扭曲了,还是图像的顶部和底部被切断了?您在哪些浏览器上试过这个?图像的分辨率是多少?一个真实的例子会很好。@GarethCornish是的,图像的顶部和底部被切断了。我已经在IE9和Chrome上试过了。即使我删除了这两个属性,它也会给我同样的结果。不适合我。我想覆盖整个背景。除了html,你确定图片本身没有拉伸吗?请检查背景url属性。尝试将选择器设置为“body”而不是“html”btw“cover”,因为属性不会拉伸图像。。。因此,它的工作原理应该是这样的,您可以通过约束任一图像的最小尺寸(例如
min height:700px;
)部分避免图像纵横比失真。大多数情况下,我使用第一个选项
background size:cover
,用于处理该图像不同纵横比的媒体查询。