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

新手上路,请多包涵

我正在尝试设置一系列带有背景图像的 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;
}

原文由 TheButlerDidIt 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 433
2 个回答

在此处 查看我对类似问题的回答。

听起来您希望背景图像在扩展到 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 得到百分比值。

原文由 cr0ybot 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题