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

2019-08-08 18:05发布

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?

2条回答
该账号已被封号
2楼-- · 2019-08-08 18:29

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>

查看更多
Rolldiameter
3楼-- · 2019-08-08 18:34

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>

查看更多
登录 后发表回答