Div 尽管使用 "background-size: cover" 背景图片仍未缩小以适合

Div background image not shrinking to fit despite using "background-size: cover"

这是原始图片 (2880 x 900):

这是它在渲染页面 (1280 x 500) 上的显示方式:

1280 x 500 是包含图像作为背景的 <div> 的尺寸。如果您注意到,渲染的背景正在被裁剪,而不是缩小以适应比原始图像小的 div 内部。我的理解是 background-size: cover 意味着在不裁剪的情况下放大或缩小图像。为什么它不起作用?

HTML

<div class="page-header-div">
    <div class="page-header-div-image-blog" style="background: url(<?php echo $bannerurl ?>) no-repeat;"></div>
    <div class="downarrow text-center downarrow1" onclick="scrollPage(this);"><i class="fa fa-chevron-down"></i></div>
</div>

CSS

.page-header-div { position: relative; }
.page-header-div-image-blog {
  background-size: cover;
  height: 100%;
}

另一个页面上完全相同的标记工作得很好!这两个页面具有用于代码段的完全相同的标签。有没有办法通过CSS解决这个问题?如果是这样,如何使用 JS 来完成它(如果可能的话,我真的想避免这种情况)。

您必须改用 background-size: contain; 并将 background-repeat 设置为 no-repeat

来自MDN background-size docs

cover: 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.

contain: 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.

另请注意,正如@zgood 指出的那样:

2880 x 900 is a different aspect ratio than your div at 1280 x 500, so event when you use contain you will have a gap

div {
  width: 1280px;
  height: 500px;
  background-image: url(http://i.stack.imgur.com/rf8Wg.jpg);
  background-size: contain;
  background-repeat: no-repeat;
}
<div></div>

另请参阅:

div {
  width: 1280px;
  height: 500px;
  background-image: url(http://i.stack.imgur.com/rf8Wg.jpg);
  background-size: 100% 100%;
  background-repeat: no-repeat;
}
<div></div>

我遇到了同样的问题。事实证明,我在背景之前声明了我的背景大小。参见示例:

没有成功:

-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background: url(../img/background.jpg) center center no-repeat;

作品:

background: url(../img/background.jpg) center center no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;