Search code examples
csssvgbackground-image

Scaling centered CSS-background SVG-image proportionally to viewport without cropping


I would like to display a SVG-circle (it's in a CSS-background) this way: it should scale to the available space of the viewport without being cropped. And, it should be centered horizontally and vertically in the viewport as well.

This is my code so far:

div {
  background-image: url("data:image/svg+xml, %3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 500 500' preserveAspectRatio='xMidYMid meet' style='position: absolute; left: 0; top: 0; width: 100%25;'%3E%3Ccircle cx='250' cy='250 ' r='249' style='stroke: %23000000; fill:none;'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center center;
  height: 99vh;
  width: 99vh;
}
<body>
  <div></div>
</body>

Unfortunately, it is not centered.


Solution

  • It's centered to the div, but the height and width are both specified in vh units, making the div a square that doesn't stretch the width of the viewport. Change the width declaration to use vw instead.

    div {
      background-image: url("data:image/svg+xml, %3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 500 500' preserveAspectRatio='xMidYMid meet' style='position: absolute; left: 0; top: 0; width: 100%25;'%3E%3Ccircle cx='250' cy='250 ' r='249' style='stroke: %23000000; fill:none;'/%3E%3C/svg%3E");
      background-repeat: no-repeat;
      background-size: contain;
      background-position: center center;
      height: 99vh;
      width: 99vw;
    }
    <body>
      <div></div>
    </body>