Search code examples
csssassbackground-image

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


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!


Solution

  • 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"