三个div定位在表格单元格内

时间:2012-12-12 12:58:20

标签: html css css3 vertical-alignment alignment

请帮我按表格对齐表格单元格中的三个div:

enter image description here

两个小div完全位于表格单元格的右上角和左下角。 一个div应该在表格单元格内垂直和水平居中。 根据单元格高度,小div应该能够重叠居中的div。

我设法调整中央div。但我不知道如何实现小div。

  <div style=" #position: absolute; #top: 50%; display: table-cell; vertical-align: middle; text-align: center; width:inherit; height:inherit;">
      <div style=" #position: relative; #top: -50%;  margin-left: auto; margin-right: auto; background-color: green ">
        first line<br>
        second line
    </div>
</div> 

这就是我现在所拥有的: http://jsfiddle.net/zm2WW/5/

由于

1 个答案:

答案 0 :(得分:3)

我清理了一下你的代码。有关演示,请参阅http://jsfiddle.net/zm2WW/12/

以下是中间表单元格现在的样子:

<table>
    <tr>
        <td>
        </td>
        <td>
            <div class="containingBlock">
                <span class="topSpan">TopSpan</span>
                <div class="centerCell">text</div>
                <span class="bottomSpan">2</span>
            </div>
        </td>
        <td></td>
    </tr>
</table>​

你的CSS:

td {
    border: 1px solid;
    width: 200px;
    height: 75px;
}

div, span {
    border: 1px solid black;
}

.containingBlock {
    display: table;
    height: 100%;
    position: relative;
    vertical-align: middle;
    width: 100%;
}

.centerCell {
    display: table-cell;
    vertical-align: middle;
    width: 100%;
}

.topSpan {
    position: absolute;
    top: 0;
}

.bottomSpan {
    bottom: 0;
    right: 0;
    position: absolute;
    right: 0
}​

这里发生的是你有一个相对包含块,它为绝对定位的跨度提供了背景。 div占据整个单元格,但其内容居中,给你相同的效果。

相关问题