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

2024-03-17

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

目前,我有:http://jsfiddle.net/ndKWN/ 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;
}

查看我对类似问题的回答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 以获得百分比值。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

CSS Div 背景图像固定高度 100% 宽度 的相关文章