Stretch a background image (SVG) to 100% width and 100% height?

泄露秘密 提交于 2019-12-11 07:56:24

问题


The behaviour I want to achieve is the width of background-size:cover;, but the height of background-size:contain; by stretching the image. I thought that background-size:100%; should do this, but look at the example - it does not.

.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>

How can I achieve the desired - stretched - result?


回答1:


Using background-size: 100%; actually means background-size: 100% auto;. Use both width and height values: background-size: 100% 100%;

Using a width value only, in which case the height defaults to auto.

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>



回答2:


This should work:

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%;
}
<div id="container1" class="container"></div>


来源:https://stackoverflow.com/questions/46978834/stretch-a-background-image-svg-to-100-width-and-100-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!