4

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?

Blackbam
  • 17,496
  • 26
  • 97
  • 150

3 Answers3

6

The selected answer is correct, BUT, somewhat incomplete: here's why...

If you want a background SVG image to stretch and fill the full container it's important to note the SVG must allow this to happen. In the SVG make sure you have ' preserveAspectRatio="none" ' added next to the viewport.

So use:

background-size: 100% 100%;

And in the SVG make sure it looks something like this:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 100" preserveAspectRatio="none">
Rmaxx
  • 1,105
  • 11
  • 22
  • Phew, I thought I was getting mad, because intentionally stretching an SVG as a background image just didn't want to happen—until I realised it must have something to do with the SVG itself. Thanks for pointing that out! – physalis Mar 15 '23 at 18:08
3

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>
myf
  • 9,874
  • 2
  • 37
  • 49
0

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>
abney317
  • 7,760
  • 6
  • 32
  • 56