CSS-如何停止带有尺寸封面的图像缩放?

时间:2019-01-31 15:06:44

标签: html css media-queries

我正在为宽度超过2560像素的屏幕创建简单的媒体。我的问题是我有标头,并且超过2600px时,我为标头设置了静态宽度,当我调整窗口大小超过2600px时,标头的宽度为2600px,但是图像正在调整大小。如何相对于标题宽度而不是屏幕宽度设置图像大小?

#header {
  position: relative;
  height: 100vh;
  .background-image {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    background-image: url('~/images/17.jpg');
    background-size: cover;
    background-attachment: fixed;
    filter: brightness(50%);
    -webkit-filter: brightness(50%);
  }
}
@media only screen and (min-width: 2600px) {
  #header {
    width: 2600px;
    margin: 0 auto;
    height: 1000px;
    .background-image {
      width: 2600px;
    }
  }
}

2 个答案:

答案 0 :(得分:1)

问题出在background-attachment: fixed;上,导致背景随着视口缩放。根据{{​​3}},

  

背景相对于视口是固定的。即使元素具有滚动机制,背景也不会随元素移动。 (这与MDN不兼容。)

显然,它也不与background-size: cover兼容。

解决方案:重置媒体查询中的background-attachment

这里是解决方法的background-clip: text
或者,对于喜欢摘要的人来说,是一个摘要(仅在编译了SCSS的情况下)。

body {
  margin: 0;
}

#header {
  position: relative;
  height: 100vh;
}
#header .background-image {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  background-image: url("https://placehold.it/900x300");
  background-size: cover;
  background-attachment: fixed;
  filter: brightness(50%);
  -webkit-filter: brightness(50%);
}

@media only screen and (min-width: 600px) {
  #header {
    width: 600px;
    margin: 0 auto;
    height: 190px;
  }
  #header .background-image {
    background-attachment: initial;   /* new */
  }
}
<section id="header">
  <div class="background-image">
    hello
  </div>
</section>

请注意,我稍微改变了尺寸以进行测试;断点现在是600px而不是2600px,因为我没有那么宽的显示器。因此,您不必复制整个代码,带有背景附件的新行就足够了。

答案 1 :(得分:0)

我会使用:

.background-image {
    width: 2600px;
    background-size: initial;  /* to use the file sizes default height/width */
    background-position: center;  /* then optionally center the image */
}

由于.background-image与#header的宽度相同,因此下一个障碍将是图像的高度,因此可能需要居中。