【发布时间】:2014-11-25 18:57:55
【问题描述】:
尝试在表格单元格中绝对定位 div 元素时,我遇到了一种奇怪的行为。为了实现绝对定位,我使用了一个带有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;
}
如您所见,包装 div 和包含表格单元格的顶部之间存在间隙。如果我将abs 元素更改为position:relative,这个差距就会消失。
那么这个差距从何而来,我该如何预防呢?
【问题讨论】: