Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center SVG text vertically in IE9

Tags:

In order to align text vertically in SVG one has to use the dominant-baseline attribute. This has already been discussed on SO (Aligning text in SVG) and is part of the specification.

My problem is with IE9 which apparently does not support dominant-baseline and a bunch of other things.

Do you have any ideas on how to approximate dominant-baseline: central in IE9?

Here is a sample that works in FF and Chrome. It does not work in IE9, Opera 11. Safari on Windows doesn't support central, but supports middle which is still good.

<?xml version="1.0"?>
<svg width="300" height="300" xmlns="http://www.w3.org/2000/svg">
    <path d="M 10 100 h 290" stroke="blue" stroke-width=".5" />
    <text x="40" y="100" font-size="16" style="dominant-baseline: auto;">
        XXX dominant-baseline: auto; XXX
    </text>

    <path d="M 10 200 h 290" stroke="blue" stroke-width=".5" />
    <text x="40" y="200" font-family="sans-serif" font-size="15" style="dominant-baseline: central;">
        XXX dominant-baseline: central XXX
    </text>
</svg>
like image 324
Tsvetomir Tsonev Avatar asked Apr 01 '11 07:04

Tsvetomir Tsonev


People also ask

How do I center text in SVG?

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%" .

What is alignment baseline?

The alignment-baseline attribute specifies how an object is aligned with respect to its parent. This property specifies which baseline of this element is to be aligned with the corresponding baseline of the parent. For example, this allows alphabetic baselines in Roman text to stay aligned across font size changes.


1 Answers

One way to accomplish this in IE is to set the position related to the size of the font:

<text font-size="WHATEVER YOU WANT" text-anchor="middle" "dy"="-.4em"> M </text>

Setting the "dy" attribute will shift the text up (if value is negative) or down (if value is positive). Setting the "text-anchor" attribute centers the text on the x axis just fine in IE. Although this might hackish, but so is IE's support of SVG!

like image 113
whyoz Avatar answered Sep 18 '22 14:09

whyoz