Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center text inside a SVG g element?

Tags:

css

svg

I tried this http://jsfiddle.net/helderdarocha/e4bAh/. But it's only centered horizontally. This is the code and JSFiddle:

  <svg width="400" height="400">
    <g class="point" transform="translate(225,217)">
      <circle></circle>
      <text class="pointIndex" y="50">
        <tspan text-anchor="middle">10</tspan>
      </text>
    </g>
  </svg>

 <style>
    .point circle {
      cursor: pointer;
      text-align: center;
      fill: #E2137E;
      r: 10;
      stroke: #333;
      stroke-width: 2px;
    }
 </style>

How to center .pointIndex inside .point?

https://jsfiddle.net/alexcheninfo/9a112b63/6/

like image 463
alexchenco Avatar asked Jan 22 '16 02:01

alexchenco


People also ask

How do I center text in SVG element?

An easy solution to center text horizontally and vertically in SVG: Set the position of the text to the absolute center of the element in which you want to center it: If it's the parent, you could just do x="50%" y ="50%" .

How do you center text within an element?

Center Align Text To just center the text inside an element, use text-align: center; This text is centered.

How do I center SVG contents?

How Do I Center An Svg In Svg? the svg as follows: You can either add this style = “text-align center:” to the div in order to insert the center text in the div, or you can assign this style = “display:block”; margin; auto”; that style = “display: block”; .


1 Answers

Finally the issue was with y="50" in the text.pointIndex , change it to y="5" to get it vertically centered

JS Fiddle - updated

.point circle {
  cursor: pointer;
  text-align: center;
  fill: #E2137E;
  r: 10;
  stroke: #333;
  stroke-width: 2px;
}
<svg width="400" height="400">
  <g class="point" transform="translate(225,217)">
    <circle></circle>
    <text class="pointIndex" y="5">
      <tspan text-anchor="middle">10</tspan>
    </text>
  </g>
</svg>
like image 197
Mi-Creativity Avatar answered Nov 10 '22 13:11

Mi-Creativity