background-image:修复过度拉伸图像

时间:2014-10-20 05:18:49

标签: css background-image

在我的投资组合中,我正在尝试实现全宽度固定(不滚动,不是视差...固定)背景图像。此图像将用作前景图像的背景。

HTML:

<header>
    <img src="assets/img/blahblah1.png">
</header>

(标题应用了背景图像,img是前景图像)

CSS:

header {
   background-image: url(../assets/img/blahblah2.jpg);
   background-attachment: fixed;
   background-position: 0 0;
   min-height: 15.625em;
   padding: 4em 0 12em;
   background-repeat: no-repeat;
   width: 100%;
   -webkit-background-size: cover;
   -ms-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;
   padding: 0;
}

然而,问题是background-attachment: fixed拉伸图像远远超过默认值。

请看这两个截图:一个没有。

<{> Screenshot background-attachment: fixed

带有默认背景图片的

Screenshot

我错过了什么?有解决方法吗?我绝对希望修复背景图片。

1 个答案:

答案 0 :(得分:0)

在玩完背景属性之后,我想我找到了一个理想的组合。

  • 使用background-size: 100%代替cover - 这会将图像与容器宽度

  • 成比例拉伸
  • 使用适当的max-width / max-height

background-attachment: fixed不应该做任何事情,但可以应用它。

实施例

背景图片 - 1000 x 540

* {
  box-sizing: border-box;
}
body {
  margin: 0;
}
header {
  margin: 0 auto;
  background: url(http://lorempixel.com/output/city-q-c-1000-540-9.jpg);
  background-size: 100%;
  background-attachment: fixed;
  width: 100%;
  max-width: 1000px; /* image width */
  background-repeat: no-repeat;
  padding: 20px;
}
img {
  max-width: 50%;
  max-height: 50%;
  display: block;
  /* remove inline gap */
}
@media screen and (max-width: 500px) {
  header {
    background-size: cover;
    background-attachment: scroll;
  }
}
<header>
  <img src="http://lorempixel.com/output/people-q-c-500-500-1.jpg">
</header>

相关问题