【问题标题】:background-size: contain height always 0背景大小:包含高度始终为 0
【发布时间】:2016-09-04 19:39:41
【问题描述】:

我正在尝试使图像具有响应性,使用 contain 作为 background-size,但高度始终为 0。我已经在父元素上设置了高度,我缺少什么?

.masthead .container {
  height: 300px;
}
.masthead-title {
  margin-top: 0;
  margin-bottom: 0;
  color: #505050;
  background-image: url('../logo.png');
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center center;
}
  <div class="masthead">
    <div class="container">
      <label for="sidebar-checkbox" class="sidebar-toggle"></label>

      <h3 class="masthead-title">
        <a href="/" title="Home"></a>
      </h3>
    </div>
  </div>

【问题讨论】:

    标签: html css responsive background-size


    【解决方案1】:

    您需要为.masthead-title 指定高度。

    .masthead .container {
        height: 300px;
        border: 1px dashed gray;     /* for demo only */
    }
    
    .masthead-title {
        margin-top: 0;
        margin-bottom: 0;
        color: #505050;
        background-image: url('http://i.imgur.com/60PVLis.png');
        background-repeat: no-repeat;
        background-size: contain;
        background-position: center center;
        height: 100%;                /* new */
    }
    <div class="masthead">
        <div class="container">
            <label for="sidebar-checkbox" class="sidebar-toggle"></label>
            <h3 class="masthead-title">
            <a href="/" title="Home"></a>
          </h3>
        </div>
    </div>

    jsFiddle

    【讨论】:

      【解决方案2】:

      问题是您用于背景图像的&lt;h3&gt; 标记的高度为零。所以要么给 .masthead-title 一个固定的高度,要么在 &lt;h3&gt; 或 &lt;a&gt; 里面做一些内容。

      选项 1:在具有属性 background-image 的元素上固定高度

      .masthead-title {
        height: 300px;
      }
      

      选项2:具有背景图像属性的元素内的内容

       <h3 class="masthead-title">
         <a href="/" title="Home">Test Test Test</a>
       </h3>
      

      选项 3: 保持容器上的固定高度,并将具有 background-image 属性的子容器设置为 100% 高度

      .masthead .container {
        height:300px;
      }
      .masthead-title {
        height:100%;
      }
      

      【讨论】:

      • 谢谢大家!我忘记在 h3 中添加内容了,非常感谢。
      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 2015-03-03
      • 1970-01-01
      相关资源
      最近更新 更多