Search code examples
csssvgsmil

How to position my svg image to the center of browser


I generated a simple svg image and loaded it to Chrome. Meant to position it to the center of browser(even when the browser resizing), but so far have failed on this.

Have referred to some articles about viewport/viewbox setting, and some Q&As on this site(https://stackoverflow.com/questions/8639383/how-do-i-center-an-svg-in-a-div;https://stackoverflow.com/questions/13373169/align-svg-to-center-of-screen), but haven't got it done. Maybe I missed something, since I am very new to this.

Here is the full code for this svg image:

<svg
   xmlns="http://www.w3.org/2000/svg"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   width="100%"
   height="100%"
   viewBox="0 -700 1080 1920"
   preserveAspectRatio="xMidYMid meet"
   version="1.1"
   id="mysvg"
>
  <g
    id="group" >
      <circle
       r="500"
       style="fill:#ffb721;fill-opacity:1"
       cy="0"
       cx="0"
       id="path" />

       <circle
       style="fill:#f71c17;fill-opacity:1;"
       id="path2"
       cx="0"
       cy="0"
       r="250" />
   </g>
</svg>

I expect this image could stay at the center of the browser, even during browser resizing.


Solution

  • I think this is what you want? The SVG will be position in the center even the browser resized and scroll

    ON GLOBAL CSS

    CSS:

    #container {
    top: 50%;
    left: 50%;
    position: fixed;
    transform: translate(-50%, -50%);
    }
    

    INSIDE SVG

    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 439.29 439.29" width="100%" height="100%">
        <g id="group">
          <circle cx="219.64" cy="219.64" r="219.64" style="fill: #ffb721" id="path"/>
          <circle cx="219.64" cy="219.64" r="108.32" style="fill: #f71c17" id="path2"/>
        </g>
      </svg>