【问题标题】:Stretch a background image (SVG) to 100% width and 100% height?将背景图像 (SVG) 拉伸到 100% 宽度和 100% 高度?
【发布时间】:2018-04-09 06:47:41
【问题描述】:

我想要实现的行为是background-size:cover;的宽度,但是background-size:contain;的高度通过拉伸图像。我认为 background-size:100%; 应该这样做,但看看这个例子 - 它没有。

.container {
   background-image:url("https://upload.wikimedia.org/wikipedia/commons/3/34/Red_star.svg");
   background-position:center center;
   background-repeat:no-repeat;
   width:300px;
   height:180px;
   background-color:#eef;
   border-bottom:1px solid #000;
}

#container1 {
  background-size:contain;
}

#container2 {
  background-size:cover;
}
#container3 {
  background-size:100%;
}
<div id="container1" class="container"></div>

<div id="container2" class="container"></div>

<div id="container3" class="container"></div>

我怎样才能达到预期的-拉伸-结果?

【问题讨论】:

    标签: html css svg background-image stretch


    【解决方案1】:

    这应该可行:

    background-size: 100% 100%;
    

    .container {
       background-image:url("https://upload.wikimedia.org/wikipedia/commons/3/34/Red_star.svg");
       background-position:center center;
       background-repeat:no-repeat;
       width:300px;
       height:180px;
       background-color:#eef;
       border-bottom:1px solid #000;
    }
    
    #container1 {
      background-size: 100% 100%;
    }
    &lt;div id="container1" class="container"&gt;&lt;/div&gt;

    【讨论】:

      【解决方案2】:

      使用background-size: 100%; 实际上意味着background-size: 100% auto;。同时使用宽度和高度值:background-size: 100% 100%;

      仅使用宽度值,在这种情况下高度默认为自动。

      https://developer.mozilla.org/en-US/docs/Web/CSS/background-size#Syntax

      .container {
         background-image:url("https://upload.wikimedia.org/wikipedia/commons/3/34/Red_star.svg");
         background-position:center center;
         background-repeat:no-repeat;
         width:300px;
         height:180px;
         background-color:#eef;
         border-bottom:1px solid #000;
      }
      
      #container1 {
        background-size:contain;
      }
      
      #container2 {
        background-size:cover;
      }
      #container3 {
        background-size: 100% 100%;
      }
      <div id="container1" class="container"></div>
      
      <div id="container2" class="container"></div>
      
      <div id="container3" class="container"></div>

      【讨论】:

        【解决方案3】:

        选择的答案是正确的,但有些不完整:这就是为什么...

        如果您希望背景 SVG 图像拉伸并填充整个容器,请务必注意 SVG 必须允许这种情况发生。在 SVG 中,确保在视口旁边添加了“preserveAspectRatio="none"”。

        所以使用:

        background-size: 100% 100%;
        

        在 SVG 中确保它看起来像这样:

        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 100" preserveAspectRatio="none">
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-05-10
          • 2012-03-21
          • 2018-01-26
          • 2013-05-06
          • 1970-01-01
          • 2018-05-30
          • 1970-01-01
          • 2023-03-10
          相关资源
          最近更新 更多