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
。
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>
另见:
关于html - 尽管使用 "background-size: cover",但 Div 背景图像不会缩小以适合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35094327/