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

51 Views Asked by At

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>

2

There are 2 best solutions below

0
ccprog On BEST ANSWER

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>

0
Lex On

Its a great question. And it looks like it is fixed to the top. But the SVG has qualities to make it responsive and center itself full screen.

    svg {
      background: gray;
      width: 100vw;
      height: 100vh;
    }

The above CSS along with the missing height and width attribute allow the SVG to scale. And it's being told to consume all available width and height which causes it to center. Removing the CSS fixes the elements at the top of the screen.

html, body {
  margin: 0;
}
<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>