【问题标题】:CSS Div Background Image Fixed Height 100% WidthCSS Div 背景图像 固定高度 100% 宽度
【发布时间】:2015-05-04 22:13:52
【问题描述】:

我正在尝试设置一系列带有背景图像的 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 { padding: 0px; margin: 0px; }?
  • body padding 和 margin 都是 0;当您在浏览器上查看宽度超过图像宽度的页面时,就会出现问题。背景图像未水平填充。

标签: html css


【解决方案1】:

查看我对类似问题的回答here

听起来您希望背景图像保持其自己的纵横比,同时扩展到 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得到百分比值。

【讨论】:

    【解决方案2】:

    http://jsfiddle.net/ndKWN/1/

    你可以使用background-size: cover;

    【讨论】:

    • 牢记background-size的支持:IE9+、Opera 10+、Firefox 4+、Chrome
    【解决方案3】:

    但问题是 .chapter 类不是动态的,你声明了一个 height:1200px

    所以最好使用 background:cover 并设置媒体查询的特定高度以获得流行的分辨率。

    【讨论】:

      猜你喜欢
      • 2018-12-08
      • 2015-03-15
      • 2013-10-24
      • 2015-06-22
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多