41

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

3 回答 3

58

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

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

The problem with this approach is that you have the container elements at a fixed height, so there can be space below if the screen is small enough.

If you want the height to keep the image's aspect ratio, you'll have to do something like what I wrote in an edit to the answer I linked to above. Set the container's height to 0 and set the padding-bottom to the percentage of the width:

.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/

You could also put the padding-bottom percentage into each #chapter style if each image has a different aspect ratio. In order to use different aspect ratios, divide the height of the original image by it's own width, and multiply by 100 to get the percentage value.

于 2013-05-02T14:12:28.333 回答
19

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

您可以使用background-size: cover;

于 2013-03-30T00:57:04.857 回答
4

But the thing is that the .chapter class is not dynamic you're declaring a height:1200px

so it's better to use background:cover and set with media queries specific height's for popular resolutions.

于 2015-05-04T14:13:52.667 回答