修复了没有设置高度的背景图片

时间:2015-08-08 01:20:17

标签: html css responsive-design background-image

我有一个div元素必须有一个固定的背景图像,所以当你滚动内容滚动它时。我的问题是我必须为特定的div元素设置一个高度才能看到它。那是因为该div中没有​​任何内容。

CSS

#top-banner{
    background-image: url(../img/grey.jpg);
    background-attachment:fixed;
    height:700px;
    background-repeat: no-repeat;
    background-size: 100% auto;
}

HTML

<div class="container-fluid">
    <div class="row" >
        <div class="col-sm-12" id="top-banner"></div>
    </div>
    <div class="row">
        <div class="col-sm-12 text-center" >
            <h1 class="band-name">Lorem Ipsum</h1>
        </div>
    </div>
</div>

这给了我更大屏幕所需的内容:

enter image description here

但是,当您缩小浏览器时,就像您在手机或平板电脑上一样,该div的高度会将所有内容推下来,使其看起来没有吸引力:

enter image description here

有没有办法不给它一个特定的高度,所以内容不会在较小的屏幕上下推但仍然有固定的背景图像?

修改 这是一个小提琴,可以看看。 http://jsfiddle.net/0xbfhwnt/

我重申:它一开始看起来不错,但是当你使浏览器变小时,图像会像预期的那样缩小,但div的高度会保持内容低于图像而不是背景图片div。

1 个答案:

答案 0 :(得分:2)

您是否考虑过媒体查询的内容?

这是第一次迭代:

http://jsfiddle.net/0xbfhwnt/2/

@media (min-width: 400px) and (max-width: 700px) {
 #top-banner{
    height: 200px;   }

}

@media (min-width: 200px) and (max-width: 399px) {
 #top-banner{
    height: 100px;   }

}

<强>更新

因此,使用媒体查询,您可以跟踪主div的大小,一直到最小的屏幕尺寸。

在这个例子中,所有的空格都消失了。

http://jsfiddle.net/0xbfhwnt/7/

@media (min-width: 500px) and (max-width: 800px) {
 #top-banner {
    height: 200px;}
}

@media (min-width: 375px) and (max-width: 499px) {
 #top-banner {
    height: 150px;}
}

@media (min-width: 250px) and (max-width: 374px) {
 #top-banner {
    height: 100px;}
}

@media (min-width: 50px) and (max-width: 249px) {
 #top-banner {
    height: 50px;}
}

当然,min-widthmax-width之间的范围越小,转换就越平滑。