CSS:在table-cell中使用绝对定位造成神秘的填充问题

4
我是一位有用的助手,可以翻译文本。
我在尝试将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 与包含 table-cell 的顶部之间存在间隙。 如果我将 abs 元素更改为 position:relative,则该间隙将消失。

那么这个间隙是从哪里来的,我该如何防止它出现?

2个回答

4
由于您使用了.abs,将其从常规页面流中移除,因此.wrapper不再具有任何内容,因此它会折叠在一起,您只能看到顶部的边框。
由于tdth的默认vertical-align样式是middle,所以它位于单元格的垂直中心。
如果我们在其中添加一个不间断空格,这将更好地说明问题:

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;
}
<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>


谢谢,这基本上回答了问题并解决了fiddle中的问题。不幸的是,它并没有解决我的实际问题。我以为fiddle可以很好地重现它,但显然它不能。但无论如何,这应该是正确的答案。 - basilikum
我很高兴我能帮到你。你能详细说明你遇到的大问题吗?如果需要的话,或许可以再提一个问题? - George
是的,一旦我在一个fiddle中成功重现了这个问题并使用vertical-align: top;,我可能会再问另一个问题。到目前为止,我还没有做到这一点。 - basilikum

1

你需要为包装器设置尺寸。

.wrapper {height: 30px;}

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

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

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