【问题标题】:Css - how to stop image scalling with size cover?Css - 如何停止使用尺寸覆盖的图像缩放?
【发布时间】:2019-01-31 23:44:41
【问题描述】:

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

#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;
    }
  }
}

【问题讨论】:

  • 你的意思是像percentage
  • 嗯,不,我想要比例的图像,但要停止缩放

标签: html css media-queries


【解决方案1】:

问题在于background-attachment: fixed;,它会导致背景随视口缩放。根据MDN

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

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

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

这里是codepen 的解决方案。
或者,对于喜欢 sn-ps 的人来说,一个 sn-p(仅使用 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>

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

【讨论】:

  • So fixed 正在解决这个问题......遗憾的是,cover 和 fixed 无法使用其容器的静态宽度,但仍然非常感谢您的回答 :)
【解决方案2】:

我会使用:

.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 具有相同的宽度,因此您的下一个障碍将是图像的高度,因此可能需要居中。

【讨论】:

  • 背景图片现在重复我不想要这个:/我想覆盖我的 2600 像素而不是整个屏幕
猜你喜欢
  • 1970-01-01
  • 2012-07-09
  • 1970-01-01
  • 2012-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多