3

Im trying to have my text justify in some svg. How is this possible? The css:

text-align:justify 

is not working,

What I found is only:

text-anchor="middle";text-anchor="start";text-anchor="end"

But this just align left, align right or centre, not justify from left to right .

Is there any solution ?

here is a live example (to check with Chrome): http://codepen.io/anon/pen/vGERRq

Thanks

Agustin Cautin
  • 411
  • 5
  • 23
tibewww
  • 593
  • 4
  • 11
  • 32

3 Answers3

1

It is possible to do this by Javascript for INLINE SVG! I've made a pen for you, to show you the principle. I was looking for something like this myself and didn't find it anywhere. It doesn't seem part of the spec, so doing it in Javascript is justified :)

This is the basic structure for a line of text to be justified, each word should be a text tag:

<g class="line" transform="translate(0,40)">
    <text>Another</text>
    <text>line</text>
    <text>of</text>
    <text>text</text>
</g>

This is the javascript-code:

var lines=document.getElementsByClassName("line");
for(var l=0;l<lines.length;l++)
{
    var line=lines[l];
    var total_width=200;
    var texts=line.getElementsByTagName("text");
    var width_of_texts=0;
    for(var i=0;i<texts.length;i++)
    {
        width_of_texts+=texts[i].getBBox().width;
    }
    if(texts.length>1)
    {
        var extra_space=(total_width-width_of_texts)/(texts.length-1);
        var x=0;
        for(var i=0;i<texts.length;i++)
        {
            texts[i].setAttribute("x",x);
            x=x+texts[i].getBBox().width+extra_space;
        }
    }
}

Here is a working example. https://codepen.io/SnoepGames/pen/zVaRoZ

Short explanation. We can get classes and elements within an inline SVG in much the same way as with HTML elements. With getBBox() we can get the width of the text in the same way for SVG text-elements as getBoundingClientRect for HTML elements. The rest is just adding up and subtracting.

You could put a data attribute in a group with class "justified lines" as well to set the width dynamically and you'd have a pretty usefull script.

The script will now justify all grouped texts with class line to a fixed width (var total_width = 200) This script does justification by adding to spaces, but you could also use this principle to do justification between letters.

Hjalmar Snoep
  • 301
  • 2
  • 6
-3

Have you tried javascript style.textAlign property

elem.style.textAlign="justify"
Vijaykrish93
  • 150
  • 8
-3

Try this

Justification changes spacing between words:

For div :

div {
text-align:justify;
text-justify: inter-word;
text-align-last:center;
/* for IE9 */
-ms-text-align-last:center;
}

text-justify: auto|inter-word|inter-ideograph|inter-cluster|distribute|kashida|trim|initial|inherit;

Refer this : http://www.w3schools.com/cssref/css3_pr_text-justify.asp

Kamuran Sönecek
  • 3,293
  • 2
  • 30
  • 57
venkat
  • 449
  • 4
  • 17