问题
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