【问题标题】:Background image only works when setting display property to list-item背景图像仅在将显示属性设置为列表项时有效
【发布时间】:2017-06-18 23:57:00
【问题描述】:

我一直在尝试将背景图片设置为 css 中的 div,即

React.createElement("div", {className: "icon"})

.icon {
    background: url("../images/icons/icon.png") 0 0 no-repeat;
}

似乎什么都没有显示。我还验证了图片的位置正确。

但是,当我将 .icon 设置为 display: list-item 时,即

.icon {
    display: list-item;
    background: url("../images/icons/icon.png") 0 0 no-repeat;
 }

图像出现在页面上。是否有任何理由显示列表项有效,但没有其他原因?有没有办法让背景图像工作而不必使用display: list-item

【问题讨论】:

    标签: css reactjs


    【解决方案1】:

    这取决于:你的.icon DIV 有内容吗?

    因为,如果 DIV 不包含任何内容,则它没有大小(即高度为零),因此您不会看到背景图像。

    但是,li 默认情况下始终至少有一行高(即为其定义的行高)和 100% 宽,即使没有内容,所以您会看到背景图像...

    【讨论】:

    • 不,图标 div 没有内容。就像它在代码 sn-p 中一样。你所说的关于列表项的内容很有意义。我尝试在我的空 div 上设置 min-width 和 min-height,但它并没有像 display: list-item 那样解决问题
    【解决方案2】:

    尝试以下方法;

    使用以下css代码创建一个div:

    div {
      height: 400px;
      width: 400px;
      background-image: url("INSERT URL HERE");
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
    }
    

    这应该会在页面上创建一个完美的正方形,并将您在引用之间发布的图像作为其背景。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-24
      • 1970-01-01
      • 1970-01-01
      • 2014-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多