Search code examples
csshtmltext-alignjustify

Text-align:justify only works on indented (complicated) HTML code, not on HTML code without whitespaces


I'm maintaining an online newspaper editor, and I've stumbled on a weird issue, where text doesn't want to be justified with text-align:justify. After a few hours of debugging, I noticed it might have something to do with the output HTML indenting (which sounds realy weird to me).

Obviously the raw HTML output of my editor page isn't indented, but a text field has a basic structure like this:

<div>
  <p>
    <span>
      <span>
        <span>
          Hello&nbsp;
        </span>
      </span>
    </span>
    <span>
      <span>
        <span>
          World.
        </span>
      </span>
    </span>
  </p>
</div>    

Every word is wrapped in 3 spans(rendered by JS/jQuery, for styles, fonts & uniformity between browsers), and I put the text-align:justify; in the <p> element.

Here's some sample code: https://jsfiddle.net/tdje0a9L/

As you can see, the text isn't justified.

But now, when i indent the exact same HTML code, it becomes justified:
https://jsfiddle.net/3v7vk24d/

I can't realy do much about the multiple span wrapping, that's just how the editor works.

Now is my question:

  • is there any way to render the output HTML indented?

    (to get my text justified)

    or

  • is there an other way to get my text justified?


Solution

  • It is because you have &nbsp; (non-breaking space) entities in you source code - that means that you code really don't have spaces between words.

    So for text-align: justify it seams to be one word.

    Your example will print: Donec quam felis as one word

    You can look in this question for some more information how you can remove your unwanted entities: How to remove &nbsp; from the end of spans with a given class?