5

我试图显示三个 div 元素从容器 div 元素的一个边缘均匀分布到另一边缘。

这是HTML代码。

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

这是CSS代码。

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

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

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

这可以正常工作,可以在这里看到:http: //jsfiddle.net/zVf4j/

但是,当我尝试使用以下 JavaScript 更新容器 div 时,子 div 元素不再从容器 div 元素的边缘散布到边缘。

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

在这种情况下,CSS 中的text-align: justify;属性似乎无效。这个问题可以在这里看到:http: //jsfiddle.net/b5gBM/

我有两个问题。

  1. 为什么使用 JavaScript 更新子 div 元素的位置会发生变化?
  2. 我们如何解决这个问题,以便子 div 元素即使在使用 JavaScript 更新后也能从容器 div 的一个边缘均匀分布到另一边缘?
4

2 回答 2

3

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>
于 2013-07-14T21:36:16.610 回答
0

I don't have an answer for question 1 but for question 2, if you are defining your divs width to be 30% then you can distribute the remaining 10% as margin to the middle div to have them all evenly spread out. So you can get rid of text-align:justify; and use this:

#container div:nth-child(2) {
    margin: 0 5%;
}

*Note that IE8 and lower don't provide :ntch-child support

Demo fiddle

于 2013-07-14T21:35:54.893 回答