CSS Div背景图像高度固定100%宽度

43

我正在尝试设置一系列具有背景图像的div,每个div都有自己固定的高度,并且可以拉伸以填满宽度,即使顶部/底部溢出被剪切。我只是不想在边缘留下空白。

目前,我有:http://jsfiddle.net/ndKWN/

CSS

#main-container {
    float: left;
    width: 100%;
    margin: 0;
    padding: 0;
    text-align: center;
}

.chapter {
    position: relative;
    height: 1400px;
    z-index: 1;
}

#chapter1 {
    background: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg) 50% 0 no-repeat fixed;
    height: 1200px;
}

#chapter2 {
    background: url(http://download.ultradownloads.com.br/wallpaper/94781_Papel-de-Parede-Homer-Simpson--94781_1680x1050.jpg) 50% 0 no-repeat fixed;
    height: 1200px;
}

"边缘的空白" ... 您是指 "全局" 的 body 边距吗?那么请尝试:body { padding: 0px; margin: 0px; } - Stefan Brendle
1
主体的填充和边距都为0;当您在宽度超过图像宽度的浏览器上查看页面时,问题就出现了。背景图像无法水平填充。 - TheButlerDidIt
3个回答

63

请查看我在类似问题这里的回答。

看起来你想让一个背景图片保持自己的纵横比,同时扩展到100%的宽度并在顶部和底部被裁剪。如果是这样的话,可以像下面这样做:

.chapter {
    position: relative;
    height: 1200px;
    z-index: 1;
}

#chapter1 {
    background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
    background-repeat: no-repeat;
    background-size: 100% auto;
    background-position: center top;
    background-attachment: fixed;
}

jsfiddle: http://jsfiddle.net/ndKWN/3/

这种方法的问题在于,您将容器元素设置为固定高度,因此如果屏幕太小,则下方可能会有空白。

如果您希望高度保持图像的宽高比,则需要执行类似我编辑过的答案中所述的操作。将容器的height设置为0,并将padding-bottom设置为宽度的百分比:

.chapter {
    position: relative;
    height: 0;
    padding-bottom: 75%;
    z-index: 1;
}

#chapter1 {
    background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
    background-repeat: no-repeat;
    background-size: 100% auto;
    background-position: center top;
    background-attachment: fixed;
}

jsfiddle: http://jsfiddle.net/ndKWN/4/

如果每张图片的宽高比不同,您也可以将padding-bottom百分比放入每个#chapter样式中。为了使用不同的宽高比,请将原始图像的高度除以其宽度,并乘以100以获取百分比值。


21

1
请注意 background-size 的支持:IE9+,Opera 10+,Firefox 4+,Chrome。 - MMM

4

但问题在于,.chapter类不是动态的,你声明了一个高度为1200像素

因此最好使用background:cover,并针对常见分辨率设置特定高度的媒体查询。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接