【问题标题】:Background image will not appear背景图片不会出现
【发布时间】:2017-02-14 03:52:12
【问题描述】:

我 100% 不知道为什么我无法显示 background-image。我尝试了多个不同的图像来排除这种情况。我还将src 更改为url,将background-sizecover 更改为auto 100%。我所做的任何事情都不会显示图像。

有人知道为什么我的背景图片不会显示吗?

#home-img {
	background-image: url("http://cosmotekcollege.com/wp-content/uploads/2015/08/ban4.png");
	background-repeat: no-repeat;
	background-size: cover;
	background-position: center;
	background-position: 50% 50%;
	width: 100%;
	height: auto;
	position: relative;
}
<div id="home-img">
</div>

这里是jsfiddle

【问题讨论】:

  • 给你的 div 一些内容或定义一个高度。它没有原样的高度
  • height: auto 不够用?
  • 如有疑问,请右键单击您的页面并执行 Inspect Element。如果您将鼠标悬停在代码中的 &lt;div&gt; 上,它将在页面上突出显示,您会发现它的高度为 0px。 height: auto; 将调整 div 的大小以适应其内容(无论如何这是默认行为),但是您的 div 没有内容。没有任何内容或设置高度,它将是 0px 高。
  • 我认为您的示例几乎可以回答这个问题。背景图像就是这样,背景图像;它不占用任何空间,因此您的 div 正在折叠到尽可能小的空间。
  • height: auto 将取决于孩子的身高。 stackoverflow.com/questions/15943009/…

标签: html css background-image


【解决方案1】:

如果您使用背景图像并且 div 中没有内容,则始终应设置高度。这是示例https://jsfiddle.net/5pphkLmt/5/

<div id="home-img">
        </div>

#home-img {
    background-image: url("http://cosmotekcollege.com/wp-content/uploads/2015/08/ban4.png");
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    background-position: 50% 50%;
    width: 100%;
    height: 540px;
    position: relative;
}

【讨论】:

    【解决方案2】:

    使用 Chrome Inspect,我将 #home-img 高度从“auto”更改为 537px,然后图像出现了。因此,更新高度是解决此问题的一种选择。

    此 SO Q&A 条目中介绍了另一个选项。

    How to get div height to auto-adjust to background size?

    【讨论】:

      【解决方案3】:

      您应该在代码中添加height 或在此DIV 中添加一些内容,只需测试height: 100px; 并享受它:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-12-06
        • 2015-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-11
        • 2012-07-12
        相关资源
        最近更新 更多