Search code examples
htmlcsssvgbackground-image

Ignore SVG aspect ratio and stretch to 100% window size


I have a svg file that a am using as a background-image. Now I would like to stretch it to the size of the window. All aspect ratios should be ignored, so the background SVG should neither use background-size: cover nor contain.

Right now I have this code, but it doesn't work.

html {
  background: url("image.svg") center no-repeat;
  width: 100%;
  height: 100%;
}

Does someone have any idea?


Solution

  • You can simply add preserveAspectRatio="none" to SVG if you don't care about aspect ratio. And setbackground-size: 100% 100%; in the CSS.

    Example:

    html {
      background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' preserveAspectRatio='none' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12,17.27L18.18,21L16.54,13.97L22,9.24L14.81,8.62L12,2L9.19,8.62L2,9.24L7.45,13.97L5.82,21L12,17.27Z'%3E%3C/path%3E%3C/svg%3E") center / 100% 100% no-repeat;
      height: 100%;
    }