响应式背景问题

Responsive background issue

我需要的是通过 CSS 响应的完整背景图片,比如 there

我在这里阅读了很多案例,也看到了一个 "best answers" 主题 Responsive css background images

但是我还是找不到适合我的解决方案。 Here's my Fiddle

和代码:

.container {
 background-image: url(http://www.spektyr.com/PrintImages/Cerulean%20Cross%203%20Large.jpg);
 background-repeat: no-repeat;
 background-size: 100%;
 background-position: center;
 height: 700px;

}

如果没有按照上面的答案中的建议设置任何高度,图像根本不会出现。当我将 window 的大小调整为更小时,图像会在上方 space 而不是每次都适合 window。

我做错了什么?

解决方案

经过几个小时的实验,解决方案是使用 padding-top 属性 而不是设置 height

只需在 .container 上使用 background-size:cover;,例如:

.container {
  background-image: url(http://www.spektyr.com/PrintImages/Cerulean%20Cross%203%20Large.jpg);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  height: 700px;
}

A keyword that is the inverse of contain. Scales the image as large as possible and maintains image aspect ratio (image doesn't get squished). The image "covers" the entire width or height of the container. When the image and container have different dimensions, the image is clipped either left/right or top/bottom.MDN Docs

Updated JSFiddle

编辑:

如果您在下面的评论中指出,无论屏幕大小如何,您都希望显示完整图像,请使用 background-size:contain;:

.container {
  background-image: url(http://www.spektyr.com/PrintImages/Cerulean%20Cross%203%20Large.jpg);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: contain;
  height: 700px;
}

A keyword that scales the image as large as possible and maintains image aspect ratio (image doesn't get squished). Image is letterboxed within the container. When the image and container have different dimensions, the empty areas (either top/bottom of left/right) are filled with the background-color. The image is automatically centered unless over-ridden by another property such as background-position.MDN Docs

Updated JSFiddle

这应该可以解决问题:

body {
    margin: 0;
}

.wrap {
    width: 100%;
}

.menu {
    top: 0;
    position: fixed;
    background-color: green;
    width: 100%;
}

.container {
    background-image: url(http://www.spektyr.com/PrintImages/Cerulean%20Cross%203%20Large.jpg);
    background-size: cover;
    padding-bottom: 100%; /* <- This value should be equal to height / width */
}
<div class="wrap">
    <nav class="menu">
        <ul>
            <li>Something</li>
        </ul>
    </nav>
    <div class="container"></div>
</div>

(另见 this Fiddle

根据您的最终目标,我想到了两种方法。第一种是使用 background-size: cover;,这将保持纵横比,但如果您有低分辨率图像,可能会导致背景图像像素化。另一种是使用background-size: 100% 100%;。请注意,在您的 fiddle 中,您有简单的 100%。通过添加 2 次,强制 X 轴和 Y 轴跨越 100% 的屏幕。

Fiddle 对于 coverhttps://jsfiddle.net/eqe3m2sn/1/

Fiddle 对于 100% 100%https://jsfiddle.net/nmofhodo/1/

将您的 background-position: center; 更改为 background-position: top;,它将在调整大小时填充上面的 space。至于尺寸,我很确定你在处理背景图片时需要设置高度。

希望对您有所帮助!