【问题标题】:Div background image not shrinking to fit despite using "background-size: cover"尽管使用“背景尺寸:封面”,但 Div 背景图像不会缩小以适应
【发布时间】:2016-05-07 18:24:36
【问题描述】:

这是原始图像 (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%;
}

在另一个页面上完全相同的标记可以正常工作!这两个页面具有用于 sn-p 的完全相同的标签。有没有办法通过 CSS 解决这个问题?如果是这样,如何使用 JS 来做这件事(如果可能的话,我真的很想避免这种情况)。

【问题讨论】:

  • 你需要background-size: contain;
  • 另外,2880 x 900 与 1280 x 500 的 div 的纵横比不同,所以即使使用 contain,也会有差距
  • 你是对的,包含也不起作用。但是,相同的图像在具有相同 div 尺寸的另一个页面上非常适合,这让我感到困惑。
  • 在问这样的问题之前检查MDN docs这么难吗?

标签: html css image background-image background-size


【解决方案1】:

我遇到了同样的问题。事实证明,我的背景尺寸是在我的背景之前声明的。见例子:

没有工作:

-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;

【讨论】:

  • 我遇到了同样的问题,这对我有用。非常令人沮丧的问题。这实际上应该是正确的答案。除非在背景之后声明背景大小,否则将封面更改为包含不会做任何事情。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    来自MDN background-size docs

    cover:与包含相反的关键字。尽可能大地缩放图像并保持图像纵横比(图像不会被压扁)。图像“覆盖”了容器的整个宽度或高度。 当图像和容器的尺寸不同时,图像会被裁剪为左/右或上/下。

    包含:尽可能大地缩放图像并保持图像纵横比(图像不会被压扁)的关键字。图像在容器内加了信箱。当图像和容器具有不同的尺寸时,空白区域(左/右的顶部/底部)用背景色填充。除非被其他属性(例如 background-position)覆盖,否则图像会自动居中。

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

    2880 x 900 与 1280 x 500 的 div 的纵横比不同,因此当您使用 contains 时,您会有一个间隙

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

    另见:

    【讨论】:

    • 它已经设置为无重复,并且在发布问题之前我已经尝试过contain,但没有成功。
    • 我知道应该存在差距,但事实并非如此。就我而言,图像只是被裁剪,这不是我想要的。结果与 contains 相同。
    • @TheLearner 所以发布一个可以重现该问题的代码 sn-p。
    • @TheLearner 在另一个页面上完全相同的标记可以正常工作!一定有不同的东西......比如拼写错误的类名或无效的标记。您可能错过了 1 页上的 CSS 导入?
    • 不确定你想要什么...我已经发布了受影响作品的 HTML 和 CSS。
    猜你喜欢
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    相关资源
    最近更新 更多