How to center a circle in an svg

16,155

Solution 1

<svg viewBox="-1 -1 2 2"> <!-- viewBox defines the coordinate system.-->
    <circle cx="0" cy="0" r="1" />
</svg>

https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/viewBox

http://jsfiddle.net/QrNnN/

Solution 2

An alternative to the viewBox variant:

<svg width="100" height="100">
  <circle cx="50%" cy="50%" r="10"/>
</svg>

The circle would however get bigger if you zoom the whole page.

Another way is to use a zero-length path with rounded linecaps, like this:

<svg viewBox="0 0 100 100">
  <path d="M50 50" stroke-linecap="round" stroke="black" 
        fill="none" vector-effects="non-scaling-stroke"
        stroke-width="20"/>
</svg>

http://jsfiddle.net/dAEB9/

Share:
16,155

Related videos on Youtube

zcaudate
Author by

zcaudate

Updated on September 16, 2022

Comments

  • zcaudate
    zcaudate over 1 year

    I'm lost as to how I can put a circle element at the center of an svg without it moving around or getting bigger and smaller as I resize the page.

    I've tried viewBox but it doesn't do what I expected.

    • Josh Crozier
      Josh Crozier over 10 years
      The viewBox would effectively center it within the SVG if you use it properly.
    • zcaudate
      zcaudate over 10 years
      oh... silly me.. =) to get a coordinate system between (-1000 -1000) and (1000 1000)... the viewBox needs to be: viewBox="-1000 -1000 2000 2000" the last two values are lengths, not coordinates
  • theman0123
    theman0123 over 4 years
    alternately: viewbox needs the stroke size added to the width and height, and the circle then needs to be offset by half the stroke size. if stroke=6 then... viewbox= -3 -3 106 106
  • nixkuroi
    nixkuroi about 4 years
    Can you use translate with percentages?