html - 尽管使用 "background-size: cover",但 Div 背景图像不会缩小以适合

标签 html css image background-image background-size

这是原始图像 (2880 x 900): enter image description here

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

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>

另见:

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

相关文章:

javascript - 复选框不想切换启用禁用字段

django - 将图像写入 Django HttpResponse() 的最佳方法

Javascript 代码在 html 下拉选项元素中不起作用

html - 如何在文本框下显示以下日期格式标签

html - 调整窗口大小时,站点缩放但随后开始从右侧裁剪

jquery - 打印页面时隐藏 jquery ui Accordion 格式

html - div 的动态 CSS 自动大小

图像下的 HTML、CSS 中心 H1 和 P

Javascript 图片加载 Facebook 风格

html - 使用像 Jade 这样的模板引擎有什么优缺点?