如何使div的背景响应?

时间:2017-05-26 19:37:51

标签: html css media-queries

我有一个水平放置在身体中间的容器,这个容器里面有一个div,这个div有一个背景, 我希望div的背景在缩小或调整窗口大小时响应,例如此网站ask.fm,我使用了background-size: cover;,但它不适用于我。

HTML

<div class="container">
  <div class="cover"></div>
</div>

CSS

.container {
  width: 851px;
  margin: 0px auto;
}

.cover {
  background-image: url("wall.jpg");
  background-size: cover;
  background-repeat: no-repeat;
  width: 100%;
  height: 300px;
}

/* Media Queries */
@media screen and (max-width: 840px) {
  .cover {
    width: 100%;
  }
  .container {
    width: 100%;
  }
}

@media screen and (max-width: 600px) {
  .container {
    padding: 0;
  }
}

1 个答案:

答案 0 :(得分:0)

我通常会对这两件事情进行组合 - 取决于屏幕尺寸 - 我会为图像/背景获取不同的src或内联取决于......

<section class="container">
<div class="inner-w">

  <figure>
    <img src="https://placehold.it/1600x900" alt="">
  </figure>

</div>
</section>



<section class="container section-name">
<div class="inner-w">

  <!-- ... -->

</div>
</section>

https://jsfiddle.net/sheriffderek/4j2avj7v/

figure {
  margin: 0;
}

figure img {
  display: block;
  width: 100%;
  height: auto;
}

.container {
  background: gray;
  border: 1px solid blue;
}

.container .inner-w {
  max-width: 400px; /* just for this example... likely 900+ */
  margin: 0 auto;
  background: red;
}

.section-name .inner-w {
  min-height: 300px; /* it needs to have some shape */

  background-image: url('http://placehold.it/1600x900');
  background-size: cover;
  background-position: center center;
}