我正在尝试使用背景图像设置一系列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;
}
Run Code Online (Sandbox Code Playgroud)
cr0*_*bot 48
请在此处查看我对类似问题的回答.
听起来你想要一个背景图像来保持它自己的宽高比,同时扩展到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;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
jsfiddle:http://jsfiddle.net/ndKWN/4/
如果每个图像具有不同的宽高比,您还可以将padding-bottom百分比放入每种#chapter样式.要使用不同的宽高比,请将原始图像的高度除以其自身的宽度,然后乘以100以获得百分比值.