如何根据下一个兄弟元素的高度自动调整DIV的高度?

4
我正在寻找一种CSS布局解决方案(IE9+),可以模仿“自动调整表格单元格”的效果,如下所示:

enter image description here

enter image description here


我只改变使用表格时底部单元格的高度,上面的单元格会自动响应这个变化。
以下是表格代码和一个JSFiddle演示,该演示随机更改底部单元格的高度。 HTML:
<div>
    <table>
        <tr>
            <td>Auto Adjust</td>
        </tr>
        <tr>
            <td id="adjust">Fixed Height</td>
        </tr>
    </table>
</div>

CSS:

td {
   border:solid 1px red
}
table {
   width:100%;
   height:100%;
}
div {
   height:300px;
   border:solid 1px blue;
}

#adjust{
   height:50px;
}

: 如何使用现代布局技术来实现相同的目标?

2个回答

4
这个怎么样? http://jsfiddle.net/NicoO/HfpL6/4/
.wrap
{
    height:300px;
    border:solid 1px blue;
}
.table {
    width:100%;
    height:100%;
    display: table;
    border-spacing: 2px;
}

.row
{
    display: table-row;
}

.cell  
{
    display: table-cell;
    border:solid 1px red;
    vertical-align: middle;
}

#adjust{
    height:50px;
}

这个html:

<div class="wrap">
    <div class="table">
        <div class="row">
            <div class="cell">
                Auto Adjust
            </div>
        </div>
        <div class="row">
            <div id="adjust" class="cell">
                Fixed Height
            </div>
        </div>
    </div>
</div>

更新

我唯一看到的另一个可能性是使用calc,但你需要更多的JS:

http://jsfiddle.net/NicoO/HfpL6/7/

你需要使用JS获取所有子元素,并为它们应用新的高度。

html, body
{
    height: 100%;
    margin:0;
    padding:0;
}

*
{
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

.wrap
{
    height:300px;
    border:solid 1px blue;
}
.table 
{
    width:100%;
    height:100%;
}

.row
{
    height: 50%; 
    position: relative;
}

.cell  
{
    border:solid 1px red;
    vertical-align: middle;
    position: absolute;
    top:2px;
    right:2px;
    bottom:2px;
    left:2px;
}

#adjust:not([style])
{
    background-color: green;

}

1
谢谢,我考虑过这个...基本上是使用表格而不是表格标记。如果找不到其他解决方案,这将是我的方法。 - Shlomi Schwartz
谢谢,我会明天接受你的答案,如果没有其他解决方案出现。 - Shlomi Schwartz

1

1
好的,我猜这个答案已经不相关了。无论如何,这是一个 JSFiddle 链接:http://jsfiddle.net/HfpL6/9/。 - Mathias
我非常喜欢那个演示,@Mathias做得很好。 - Nico O

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接