Ishita Ishita - 2 months ago 9
CSS Question

SVG text - make text appear in 2 lines

I have a SVH text element below:

JSFiddle - http://jsfiddle.net/E4VvX/

<text y="9" x="0" dy=".71em" style="text-anchor: middle; max-width: 30px;width: 30px;white-space: pre-wrap;" >Jul 2014</text>


The text appear in 1 line like this: ----->
enter image description here

but I want the text to render in 2 lines like this: ----->
enter image description here

How can I achieve that?

Answer

You will need to wrap each piece to text in a tspan, set the d attribute to 0 and the dy attribute to move it down.

JSFiddle

SVG

<svg width="100px" height="100px">
    <text class='dt'><tspan x="0" dy="0em">Jul</tspan><tspan x="0" dy="1em">2014</tspan></text>
</svg>

CSS

.dt {
    text-anchor: middle;
    -webkit-transform: translate(50px,50px);
       -moz-transform: translate(50px,50px);
        -ms-transform: translate(50px,50px);
         -o-transform: translate(50px,50px);
            transform: translate(50px,50px);
}

UPDATE:

This can also do something similar using foreignObject, at the cost of Internet Explorer 9 support.

JSFiddle

SVG

<svg width="100px" height="100px">
    <foreignObject width="40px" height="40px" requiredExtensions="http://www.w3.org/1999/xhtml">
        <body xmlns="http://www.w3.org/1999/xhtml">Jul 2014</body>
    </foreignObject>
</svg>

CSS

foreignObject {
    text-align: center;
    -webkit-transform: translate(50px,50px);
       -moz-transform: translate(50px,50px);
        -ms-transform: translate(50px,50px);
         -o-transform: translate(50px,50px);
            transform: translate(50px,50px);
}