Home > Blockchain >  Make background image cover div by stretching, not maintaining aspect ratio
Make background image cover div by stretching, not maintaining aspect ratio

Time:10-27

How do I make a background image cover the div by stretching, so the whole image is always visible, not like background-size: cover, where the aspect ratio does not change?

It's not a fixed width, it has to be responsive.

div {
  position: relative;

  &:after {
    content: ' ';
    display: block;
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    opacity: 0.3;
    background-image: url('/something.svg');
    background-repeat: no-repeat;
    background-position: 0 0;
    background-size: cover;
 }
}

I tried background-size: 100% 100%, also tried with img tag.

Thank you!

CodePudding user response:

If Stretching is not an issue then for img tag

<style>
img{
  /*
  Control only width or height if u don't want it to stretch. If that's not a problem then you can
  control both of it */
  width:100%;
  height:100%;
}
</style>

<img src="/something.svg" /> 

For background images :

<style>
div{
width:100%;
height:100%;
background:url("/something.svg");
background-size:100%;
background-repeat:no-repeat;
}
</style>

<div></div>

CodePudding user response:

Turns out there was also a problem in the actual svg. The solution below:

div {
  position: relative;

  &:after {
    content: '';
    display: block;
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    opacity: 0.5;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: 100% 100%;
  }
}

I removed the height and width parameters from my svg and also added: preserveAspectRatio="none"

  • Related