2

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?

Cute_Ninja
  • 4,742
  • 4
  • 39
  • 63

1 Answers1

2

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

.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);
}
<svg width="100px" height="100px">
    <text class='dt'><tspan x="0" dy="0em">Jul</tspan><tspan x="0" dy="1em">2014</tspan></text>
</svg>

UPDATE:

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

JSFiddle

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);
}
<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>
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
  • Thank you Alexander. is there any other way to achieve the same? i.e. Can we do that without inserting another element inside text? – Cute_Ninja Jul 05 '14 at 00:05
  • @Ishita No, but a similar affect can be done using `foreignObject`. There's more overhead to use it, but I added it to my answer just in case. – Alexander O'Mara Jul 05 '14 at 00:16
  • @AlexanderO'Mara is correct. The basic premise is that SVG was never intended as a composition engine, deciding when and where and how to break lines. This is a much more complex thing as it could involve hyphenation rules specific for languages. foreignObject uses the composition rules built into the browser, unless you do that you have to decide in your SVG how to break it. – Kevin Brown Jul 05 '14 at 18:29