Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center text in SVG?

Tags:

html

svg

I need to center text horizontally inside tag in SVG object without need to define x coordinate. I'm trying to find an alternative to text-align: center in CSS. I've already used text-anchor: middle but it doesn't work. I have this code

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="0%" y2="100%">
 <stop offset="0" stop-color="#FFE89C" stop-opacity="1"/>
 <stop offset="0.2" stop-color="#FFE192" stop-opacity="1"/>
 <stop offset="0.4" stop-color="#ffd47a" stop-opacity="1"/>
 <stop offset="0.6" stop-color="#ffc967" stop-opacity="1"/>
 <stop offset="0.8" stop-color="#febd52" stop-opacity="1"/>
 <stop offset="1" stop-color="#fdba4c" stop-opacity="1"/>
</linearGradient>
</defs>
<text fill="url(#grad1)" x="73" y="50">50</text>
</svg>
like image 678
Andrew Avatar asked Jul 04 '15 18:07

Andrew


1 Answers

The text is centered relatively x-axis, and I want that it' center relatively parent SVG container, otherwise it turn out that if the length of text content changes, it will be necessary to change the x coordinate.

You just need to position the text at a location halfway across the viewBox. Then if you use text-anchor="middle", the text will stay centred.

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 150 60">
  <defs>
    <linearGradient id="grad1" x1="0%" y1="0%" x2="0%" y2="100%">
      <stop offset="0" stop-color="#FFE89C" stop-opacity="1"/>
      <stop offset="0.2" stop-color="#FFE192" stop-opacity="1"/>
      <stop offset="0.4" stop-color="#ffd47a" stop-opacity="1"/>
      <stop offset="0.6" stop-color="#ffc967" stop-opacity="1"/>
      <stop offset="0.8" stop-color="#febd52" stop-opacity="1"/>
      <stop offset="1" stop-color="#fdba4c" stop-opacity="1"/>
    </linearGradient>
  </defs>

  <text fill="url(#grad1)" x="75" y="50" text-anchor="middle"font-size="40">50</text>
</svg>
like image 156
Paul LeBeau Avatar answered Oct 02 '22 08:10

Paul LeBeau