Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Justify JavaScript updated child div elements inside a parent div element

I am trying to display three div elements spread out uniformly from one edge to the other edge of a container div element.

Here is the HTML code.

<body>
    <div id="container" width="50%">
        <div>foo</div>
        <div>bar</div>
        <div>baz</div>
        <div class="stretch"></div>
    </div>
</body>

Here is the CSS code.

#container {
    margin: 10%;
    background: lightblue;
    text-align: justify;
}

#container div {
    display: inline-block;
    width: 30%;
    background: gray;
}

#container div.stretch {
    width: 100%;
    height: 0;
}

This works fine as can be seen here: http://jsfiddle.net/zVf4j/

However, when I try to update the container div using the following JavaScript, the child div elements no longer spread out from edge to edge of the container div element.

var containerDiv = document.getElementById('container')
containerDiv.innerHTML =
    '<div>fox</div>' +
    '<div>bay</div>' +
    '<div>baz</div>' +
    '<div class="stretch"></div>'

The text-align: justify; property in CSS seems to have no effect in this case. The issue can be seen here: http://jsfiddle.net/b5gBM/

I have two questions.

  1. Why does the placement of the child div elements change when they are updated with JavaScript?
  2. How can we fix this issue so that the child div elements evenly spread out from one edge of the container div to its other edge even after they are updated with JavaScript?
like image 228
Susam Pal Avatar asked Oct 22 '22 05:10

Susam Pal


1 Answers

The problem is easily fixed. You just need to add a space after the divs you are adding through JS and want to justify. Live Demo: http://jsfiddle.net/b5gBM/9/

var containerDiv = document.getElementById('container')
containerDiv.innerHTML =
    '<div>fox</div> ' +
    '<div>bay</div> ' +
    '<div>baz</div> ' +
    '<div class="stretch"></div>'

The issue is caused by whitespace. When added through JS, there is no whitespace between the divs. Think about it like text (inline). If you put three letters next to each other and wanted to justify them, it wouldn't work. It would be treated as one word. But when you put a space between them, then they're treated as three separate words and would become justified.

You can see the same issue without JS. If you write the code without any spaces it will not justify either: http://jsfiddle.net/zVf4j/1/

<div>foo</div><div>bar</div><div>baz</div>
like image 153
tw16 Avatar answered Oct 27 '22 10:10

tw16