2

这是jsFiddle

假设我有以下 HTML:

<div class="Trigger">click here</div>

<div id="TheContainer">
    <div class="One">this is some text</div>
    <input type="button" class="Two" value="button 1" />
    <input type="button" class="Three" value="button 2" />
</div>

和以下CSS:

#TheContainer{
    width:500px;
    height:40px;
    padding:10px 30px;  
    display:none;
    background:red;}

.One{float:left;}
.Two{float:left;}
.Three{float:left;}

我使用以下 javascript 来显示/隐藏容器:

$(document).ready(function () {

    $('.Trigger').click(function () {

        var TheContainer = $('#TheContainer');

        if (TheContainer.is(':visible') === false) {
            TheContainer.show();  
        } else {
            TheContainer.hide();
        }       
    });
});

如您所见,我们有一个固定宽度的隐藏容器,其中包含 3 个元素:1 个 div 和 2 个按钮,所有 3 个元素的大小都是可变的,因为这些元素的文本在运行时会发生变化。

我希望将 3 个子元素水平分布在容器内。我环顾四周,由于各种原因,现有的解决方案似乎都不适用于这种特殊情况。

如何仅使用 CSS 水平且均匀地分布这些元素? 注意:我知道我可以在 jQuery 中通过计算宽度然后绝对设置位置来做到这一点,但我正在寻找是否有仅 CSS 的解决方案。

谢谢

4

3 回答 3

2

我相信这就是你要找的东西:http: //jsfiddle.net/gq8s4/5/

它涉及在每个按钮周围创建一个 div,因此按钮本身并不是很宽。

<div id="button1"><input type="button" class="Two" value="button 1" /></div>
于 2013-04-29T16:53:49.833 回答
0

编辑:调整对新细节的回答。

http://jsfiddle.net/gq8s4/3/

.triple-container {
    float: left;
    width: 33.333333%;
    text-align: center;
    border: 1px solid yellow;
    box-sizing: border-box;
}

.One{
    text-align: center;
    width: 60px;
    margin: 0 auto;
}

.Two{
    width: 20px;  
}

.Three{
    width: 20px;
}
于 2013-04-29T16:46:04.997 回答
0

Flexbox 几乎与您将要获得的一样接近。

http://tinker.io/eb980

#TheContainer {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-pack: justify;
  -moz-box-pack: justify;
  -ms-flex-pack: justify;
  -webkit-justify-content: space-between;
  justify-content: space-between;
    width: 100%; /* for old Firefox */
}

支持:Firefox、Safari、Chrome、Opera、IE10。 http://caniuse.com/flexbox

如果您愿意添加额外的标记,您可以使用它来伪造它,display: table-cell但它并不完美:

http://tinker.io/eb980/2

#TheContainer {
    width: 100%;
    display: table;
}

div {
    display: table-cell;
    width: 33%;
}

div:nth-child(2) {
    text-align: center;
}

div:last-child {
    text-align: right;
}

<div id="TheContainer">
    <div class="One">this is some text</div>
    <div><input type="button" class="Two" value="button 1" /></div>
    <div><input type="button" class="Three" value="button 2" /></div>
</div>
于 2013-04-29T16:48:33.503 回答