【问题标题】:Make background image both fixed and fit container dimensions使背景图像既固定又适合容器尺寸
【发布时间】:2015-04-03 16:44:38
【问题描述】:

我想为容器内的 div 设置 fixed 背景(我使用的是 Bootstrap 3)。

我想制作一个div,桌面屏幕高度为 50%(移动设备上为 100%),背景图像固定。这个div 位于引导容器内,因此它没有 100% 的宽度或高度。参考行为here

但是,当我制作背景图片fixed 时,它会占据整个页面,我无法将其同时 固定并调整大小以适应容器宽度。有解决办法吗?

HTML:

<div class="container half-height">
  <div class="image" style="background-image:url(https://farm6.staticflickr.com/5140/5555177351_06069b3e9b_o.jpg)">
    <div class="description text-center">
      <h1>Title</h1>
      <div class="text-center typl8-delta">Description</div>
    </div>
  </div>
</div>

CSS:

.image{
  width:100%; height:100%; background: #eee;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
  background-attachment: fixed;
  position: relative;
}
.half-height{
  height: 50%;
}
@media (max-width: 768px) {
  .half-height{
    height: 100%;
  }
}
.description{
  position: absolute;
  bottom: 0;
  width: 100%;
  text-align: center;
  margin-bottom: 20px;
} 

【问题讨论】:

  • 你可以使用 background-size:cover;
  • 我确实使用了它,但它并没有改变任何东西(除非我设置了background-attachment: scroll

标签: html css twitter-bootstrap


【解决方案1】:

也许这有帮助。

HTML:

 <div class="container half-height main-box">
    <div class="description text-center">
        <h1>Title</h1>
        <div class="text-center typl8-delta">Description</div>
    </div>
    <div class="background-image">
        <div class="image">
        </div>
    </div>
</div>

CSS:

html, body {
    height: 1500px;
}

.half-height {
    height: 50vh;
}

@media (max-width: 768px) {
    .half-height {
        height: 100vh;
    }
}


.main-box {
    position: relative;
}

    .main-box .description {
        position: absolute;
        bottom: 20px;
        width: 100%;
        text-align: center;
        z-index: 10;
        color: #fff;
    }


    .main-box .background-image {
        display: block;
        position: relative;
        height: 100%;
    }

        .main-box .background-image .image {
            width: 100%;
            height: 100%;
            background: #eee;
            background-size: cover;
            background-repeat: no-repeat;
            background-position: center center;
            background-attachment: fixed;
            position: relative;
            background-image: url(https://farm6.staticflickr.com/5140/5555177351_06069b3e9b_o.jpg);
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 2013-02-24
    相关资源
    最近更新 更多