查看我对类似问题的回答here https://stackoverflow.com/a/14446663/900971.
听起来您希望背景图像保持其自身的纵横比,同时扩展到 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/ 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/ http://jsfiddle.net/ndKWN/4/
你也可以把padding-bottom
每项的百分比#chapter
样式(如果每个图像具有不同的长宽比)。为了使用不同的宽高比,请将原始图像的高度除以其本身的宽度,然后乘以 100 以获得百分比值。