skip to Main Content

I am trying to center text in a SVG circle.
Looked att previous solutions, however can’t make it work.

How can I get the following example center the ‘X’ i the circle not modifying the x/y coordinates or font size?

The red cross indicating the middle.

<svg width="200px" height="200px">
  <circle r="50" cx="100" cy="100"></circle>  
  <text x="100" y="100" fill="white" 
       font-size="100" text-anchor="middle" dominant-baseline="middle" 
       font-family="Verdana">X</text>  
  <line x1="50" y1="100" x2="150" y2="100" stroke="red" stroke-width="2"></line>
  <line x1="100" y1="50" x2="100" y2="150" stroke="red" stroke-width="2"></line>     
</svg>

3

Answers


  1. You can adjust the dy attribute of the <text> element to move the text slightly upward. Then dy attribute controls the vertical offset of the text relative to the y-coordinate. look at the example:

    <svg width="200px" height="200px">
        <circle r="50" cx="100" cy="100"></circle>  
        <text x="100" y="100" fill="white" font-size="100" text-anchor="middle" dominant-baseline="middle" font-family="Verdana" dy=".10em">X</text>  
        <line x1="50" y1="100" x2="150" y2="100" stroke="red" stroke-width="2"></line>
        <line x1="100" y1="50" x2="100" y2="150" stroke="red" stroke-width="2"></line>     
    </svg>
    Login or Signup to reply.
  2. You forget to use a viewbox (and that’s really bad :/)

    You may simply adjust your text y position… ?

    svg {
      width      : 200px;
      height     : 200px;
      background : yellow;
      }
    svg circle {
      fill       : black;
      }
    svg text {
      font-family : verdana;
      fill        : lightskyblue; 
      text-anchor : middle;
      }
    svg line {
      stroke       : red;
      stroke-width : 2;
      }
    <svg viewbox="50 50 100 100" >
      <circle cx="100" cy="100" r="50"            ></circle>  
      <text    x="100"  y="136" font-size="100"   >X</text>  
      <line   x1="50"  y1="100" x2="150" y2="100" ></line>
      <line   x1="100" y1="50"  x2="100" y2="150" ></line>     
    </svg>
    Login or Signup to reply.
  3. It is the dominant-baseline attribute that controls how the text is placed, but in the end it depends on the font that you are using. Sometimes the value central is better when you have a capital letter.

    <svg width="200" height="200">
      <circle r="50" cx="100" cy="100"/>  
      <text x="100" y="100" fill="white" font-size="100" text-anchor="middle"
        dominant-baseline="central" font-family="Verdana">X</text>  
      <line x1="50" y1="100" x2="150" y2="100" stroke="red" stroke-width="2"/>
      <line x1="100" y1="50" x2="100" y2="150" stroke="red" stroke-width="2"/>     
    </svg>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search