【问题标题】:CSS background-image width 100% height auto [duplicate]CSS背景图像宽度100%高度自动[重复]
【发布时间】:2018-12-08 16:36:24
【问题描述】:

我需要某种优雅的解决方案来实现背景图像宽度 100% 高度自动。它必须与使用图像 src 时的行为方式相同。我将使用 stackoverflow 上另一个问题的示例,因为那里的答案对我不起作用,也根本无法正常工作。

注意:我将把它放在具有自动宽度的 CSS 网格中,并且图像本身将具有边框。

如果有js解决方案,只要能用,我都不介意。

#image {
    background-image: url(http://www.w3schools.com/css/trolltunga.jpg);
    background-size: 100% auto;
    background-position: center top;
    background-repeat: no-repeat;
    width: 100%;
    height: auto;
}
<div id="image">some content here</div>

【问题讨论】:

  • 你说的表现得好像你使用图像src是什么意思?您想让div 的高度适应背景图像的高度吗?这是不可能的。
  • @liroP,不错。我怎么会错过这个。似乎填充技巧可以完成这项工作,我可以为此做一个 js。我认为所有答案都与填充技巧有关。

标签: javascript css


【解决方案1】:

**<div id="image">some content here</div>** Div 正在根据其拥有的内容获取高度。它无法计算自动高度。背景将检查 div 的高度,并在此基础上显示图像。因此设置 height:100% 或 height:auto 不会计算出背景图像的高度。

您必须通过为 div 提供一些填充或设置其高度来自动排列高度。

【讨论】:

    【解决方案2】:

    您可以使用基于百分比的填充值来设置容器高度。 这样,您的容器将保持背景图像的纵横比。 如果要在其中添加内容,还需要添加具有绝对定位的子元素。

    #image {
        background-image: url(http://www.w3schools.com/css/trolltunga.jpg);
        background-size: 100% auto;
        background-position: center top;
        background-repeat: no-repeat;
        width: 100%;
        height: auto;
        padding-top: 29.9%;
        position: relative;
    }
    
    #image .child {
      position: absolute;
      top: 0;
      left: 0;
    }
    <div id="image">
      <div class="child">some content here</div>
    </div>

    【讨论】:

      【解决方案3】:

      #image {
          background-image: url(http://www.w3schools.com/css/trolltunga.jpg);
              background-size: cover;
          background-repeat: no-repeat;
          width: 100%;
          height: 0;
          padding-top: 30%;
      }
      &lt;div id="image"&gt;some content here&lt;/div&gt;

      你只需要知道图像比例

      for ex the image ratio was 1000x300
      to get the padding-top (percentage) required use formula (300/1000 * 100)
      

      【讨论】:

        【解决方案4】:

        您可以使用-webkit-fill-available。它将给出预期的结果。但它只适用于 Chrome 和 Safari

        #image {
            background-image: url(http://www.w3schools.com/css/trolltunga.jpg);
            background-size: 100% auto;
            background-position: center top;
            background-repeat: no-repeat;
            width: 100%;
            height: -webkit-fill-available;
        }
        &lt;div id="image"&gt;some content here&lt;/div&gt;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-04-09
          • 1970-01-01
          • 1970-01-01
          • 2012-08-18
          • 2015-06-22
          • 2017-06-19
          • 1970-01-01
          相关资源
          最近更新 更多