div全宽度的响应背景图像

时间:2013-06-29 17:40:51

标签: html css twitter-bootstrap responsive-design background-image

我正在试图弄清楚如何在div全宽和响应中制作背景图像。背景图像在页面宽度上扩展(并且响应),但图像的高度不是其全高。似乎它正以某种方式被切断。我正在使用bootstrap框架,我试图这样做的原因是我想在图像上叠加一些文本。我尝试了很多不同的东西,但似乎无法弄明白,帮助!

<div class="bg-image">
  <div class="container">
    <div class="row-fluid">
      <div class="span12">
        <h1>This is some text</h1>
      </div>
    </div>
  </div>
</div>


  .bg-image {
  background: url(img/image.jpg) no-repeat center top;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  max-height: 450px;
  }

3 个答案:

答案 0 :(得分:14)

这是获得所需设计的一种方法。

从以下HTML开始:

<div class="container">
    <div class="row-fluid">
        <div class="span12">
            <div class="nav">nav area</div>
            <div class="bg-image">
                <img src="http://unplugged.ee/wp-content/uploads/2013/03/frank2.jpg">
                 <h1>This is centered text.</h1>
            </div>
            <div class="main">main area</div>
        </div>
    </div>
</div>

请注意,背景图片现在是文档常规流程的一部分。

应用以下CSS:

.bg-image {
    position: relative;
}
.bg-image img {
    display: block;
    width: 100%;
    max-width: 1200px; /* corresponds to max height of 450px */
    margin: 0 auto;
}
.bg-image h1 {
    position: absolute;
    text-align: center;
    bottom: 0;
    left: 0;
    right: 0;
    color: white;
}
.nav, .main {
    background-color: #f6f6f6;
    text-align: center;
}

如何运作

图像设置为宽度为100%的常规流内容,因此它将根据父容器的宽度进行自我调整。但是,您希望高度不超过450px,这对应于1200px的图像宽度,因此将图像的最大宽度设置为1200px。您可以使用display: blockmargin: 0 auto保持图片居中。

使用绝对定位在文本上绘制文本。在最简单的情况下,我将h1元素拉伸为父级的全宽并使用text-align: center 使文本居中。使用顶部或底部偏移将文本放置在需要的位置。

如果横幅图像的宽高比会有所不同,则需要使用jQuery / Javascript动态调整.bg-image img的最大宽度值,否则,这种方法可以提供很多功能。

请参阅演示:http://jsfiddle.net/audetwebdesign/EGgaN/

答案 1 :(得分:7)

当您使用background-size: cover时,背景图像将自动拉伸以覆盖整个容器。然而,长宽比保持不变,因此除非图像的宽高比和应用的元素相同,否则您将始终丢失部分图像。

我认为有两种方法可以解决这个问题:

  • 通过设置不保持图像的宽高比 background-size: 100% 100%这也将使图像覆盖 整个容器,但不会保持这个比例。坏处 是这会扭曲你的形象,因此可能看起来很奇怪, 取决于图像。有了你在小提琴中使用的图像,我 我认为你可以逃脱它。

  • 您还可以使用javascript 计算和设置元素的高度 在宽度上,它与图像的比例相同。这个 计算必须在加载和调整大小时完成。它应该是 只需几行代码即可轻松完成(如果您需要,请随时询问 例)。这种方法的缺点是你的宽度可能会变大 非常小(在移动设备上),因此计算出的高度 也可能导致容器内容溢出。这个 也可以通过改变内容的大小来解决 某些东西,但它增加了解决方案/

  • 的一些复杂性

答案 2 :(得分:0)

I also tried this style for ionic hybrid app background. this is also having style for background blur effect.

.bg-image {
   position: absolute;
   background: url(../img/bglogin.jpg) no-repeat;
   height: 100%;
   width: 100%;
   background-size: cover;
   bottom: 0px;
   margin: 0 auto;
   background-position: 50%;


  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);

}

相关问题