Trying to center an svg circle inside a div

Sunny

I have a simple markup:

 <div style="background-color:red;">
    <svg>
         <circle cx="76" cy="76" r="71" 
           style="fill:yellow;stroke:purple;stroke-width:10" />
    </svg>
 </div>

See the jsfiddle here

I cannot understand the truncation of the circle at the bottom. All I want is a div with an SVG circle exactly centered. I have tried setting box-sizing and paddings but to no avail.

Paul LeBeau

The reason for your problems is because you have not specified a size for your SVG. When you don't supply a size, the browser will give it a default size of 300x150.

So your circle at y=76 with radius 71 and stroke width 10 is going to extend down to 76+71+5 = 152, meaning the bottom of the circle is slightly clipped.

<div style="background-color:red;">
  <svg>
    <circle cx="76" cy="76" r="71" 
            style="fill:yellow;stroke:purple;stroke-width:10" />
  </svg>
</div>

If you need the circle to be exactly that size (ie. 152 pixels), then you should make that the width and height of the SVG.

<div style="background-color:red;">
  <svg width="152px" height="152px">
    <circle cx="76" cy="76" r="71" 
            style="fill:yellow;stroke:purple;stroke-width:10" />
  </svg>
</div>

That solves your size problem. To centre the SVG there are a couple of solutions:

  1. Use CSS margin to centre the SVG in the div.

svg {
  display: block;
  margin: 0 auto;
}
<div style="background-color:red;">
  <svg width="152px" height="152px">
    <circle cx="76" cy="76" r="71" 
            style="fill:yellow;stroke:purple;stroke-width:10" />
  </svg>
</div>

  1. Give the SVG a viewBox and have the browser automatically fit the SVG into the div. The advantage of this approach is that the SVG will automatically scale and centre within the div no matter how its size changes.

div {
  height: 400px;
}
<div style="background-color:red;">
  <svg width="100%" height="100%" viewBox="0 0 152 152">
    <circle cx="76" cy="76" r="71" 
            style="fill:yellow;stroke:purple;stroke-width:10" />
  </svg>
</div>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related