svgviewbox

Why does y=0 does not stick the svg-circle to the top when viewBox starts at 0


It basically have a small html-file which contains this html:

<svg viewBox="0 0 400 15">
  <circle cx="200" cy="0" r="5" fill="black"/>
  <line x1="0" x2="400" y1="0" y2="0" stroke="black">
</svg>

<style>
html, body {
  margin: 0;
}
svg {
  background: gray;
  width: 100vw;
  height: 100vh;
}
</style>

Yet the output looks like this: enter image description here

I would have expected the line and the center of the circle to stick to the top. As the y-coordinates are 0 in a coordinate space that starts at 0 as defined in the viewBox=0 0 400 15.

What am I missing here?

html, body {
  margin: 0;
}
svg {
  background: gray;
  width: 100vw;
  height: 100vh;
}
<svg viewBox="0 0 400 15">
  <circle cx="200" cy="0" r="5" fill="black"/>
  <line x1="0" x2="400" y1="0" y2="0" stroke="black">
</svg>


Solution

  • The aspect ratio of the viewBox (the area of the SVG canvas to be rendered) and the viewport (the area it is rendered into, defined by CSS width and height) do not match. In this case, the attribute preserveAspectRatio decides where the canvas is positioned and at what size.

    The default value, if the attribute is missing, is "xMidYMid meet", which means: place it into the middle at maximum size that fits. To move it to the top of the viewport, set preserveAspectRatio="xMidYMin meet".

    html, body {
      margin: 0;
    }
    svg {
      background: gray;
      width: 100vw;
      height: 100vh;
    }
    <svg viewBox="0 0 400 15" preserveAspectRatio="xMidYMin meet">
      <circle cx="200" cy="0" r="5" fill="black"/>
      <line x1="0" x2="400" y1="0" y2="0" stroke="black">
    </svg>