CSS:表格单元格中绝对位置的神秘填充

时间:2014-11-25 10:52:50

标签: html css

在尝试将div元素绝对放置在table-cell中时,我遇到了一种奇怪的行为。为了实现绝对定位,我使用了一个带有position:relative的包装div元素:

HTML

<table>
    <colgroup>
        <col width="200px"></col>
        <col width="300px"></col>
    </colgroup>
    <thead>
        <tr>
            <th>Caption 1</th>
            <th>Caption 2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><div class="wrapper"><div class="abs">abs</div></div></td>
            <td>Content 2</td>
        </tr>
    </tbody>    
</table>

CSS

table {
     width: 100%;
     border-collapse: collapse;
     table-layout: fixed;
}

th, td {
    border-bottom: 1px solid black;
    padding: 0;
    margin: 0;
}

.wrapper {
    background-color: green;
    position: relative;
    width: 100%;
    border-top: 1px solid blue;
}

.abs {
    position: absolute;
    margin: 0px;
    padding: 0px;
    background-color: red;
}

FIDDLE

正如您所看到的,包装div与包含表格单元格的顶部之间存在差距。如果我将abs元素更改为position:relative,则此差距将消失。

那么这个差距来自哪里,我该如何预防呢?

2 个答案:

答案 0 :(得分:4)

由于您从正​​常页面流中取出.abs.wrapper不再有任何内容,因此它会自行折叠,您看到的就是它顶部的边框。

它位于单元格的垂直中间,因为middlevertical-aligntd的默认th样式。

如果我们在混音中添加一个不间断的空格,可以更好地证明这一点:

&#13;
&#13;
table {
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed;
}
th, td {
    border-bottom: 1px solid black;
    padding: 0;
    margin: 0;
}
.wrapper {
    background-color: green;
    position: relative;
    width: 100%;
    border-top: 1px solid blue;
}
.abs {
    position: absolute;
    top:0;
    margin: 0px;
    padding: 0px;
    background-color: red;
}
&#13;
<table>
    <colgroup>
        <col width="200px"></col>
        <col width="300px"></col>
    </colgroup>
    <thead>
        <tr>
            <th>Caption 1</th>
            <th>Caption 2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <div class="wrapper">&nbsp;
                    <div class="abs">abs</div>
                </div>
            </td>
            <td>Content 2</td>
        </tr>
    </tbody>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您必须将尺寸设置为包装,

.wrapper {height: 30px;}

http://jsfiddle.net/b1j2gbn3/2/

否则,.wrapper高度为0,表格单元格默认为vertical-align: middle;,因此蓝色边框位于单元格的中间。