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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With