zcaudate
zcaudate

Reputation: 14258

How to center a circle in an svg

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.

Upvotes: 7

Views: 24043

Answers (3)

Matěj Kříž
Matěj Kříž

Reputation: 1228

Put your circle in group <g> and use transform="translate(x, y)".

<svg viewBox="0 0 400 400">
  <g transform="translate(200, 200)">
    <circle cx="0" cy="0" r="200" style="" fill="darkOrange"></circle>
  </g>
</svg>

Result:
enter image description here

Simple example on JSFiddle:
https://jsfiddle.net/mattez/0p2pstrf/

Upvotes: 1

Erik Dahlstr&#246;m
Erik Dahlstr&#246;m

Reputation: 60966

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/

Upvotes: 14

bjb568
bjb568

Reputation: 11488

<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/

Upvotes: 7

Related Questions