【问题标题】:CSS: mysterious padding with postion absolute in table-cellCSS:表格单元格中具有绝对位置的神秘填充
【发布时间】: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;
}

FIDDLE

如您所见,包装 div 和包含表格单元格的顶部之间存在间隙。如果我将abs 元素更改为position:relative,这个差距就会消失。

那么这个差距从何而来,我该如何预防呢?

【问题讨论】:

    标签: html css


    【解决方案1】:

    由于您将.abs 排除在正常页面流之外,.wrapper 不再有任何内容,因此它会自行折叠,您看到的只是顶部的边框。

    它位于单元格的垂直中间,因为middletdths 的默认vertical-align 样式。

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

    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>

    【讨论】:

    • 谢谢,这几乎回答了这个问题,它解决了小提琴中的问题。不幸的是,它并没有解决我的实际问题。我认为小提琴会很好地再现它,但显然它没有。但无论如何,这应该是正确的答案。
    • 我很高兴能帮上忙。你能扩展你更大的问题吗?如果合适,也许再问一个问题?
    • 是的,一旦我设法在vertical-align: top; 中重现了这个问题,我可能会问另一个问题。到目前为止,我仍然无法做到这一点。
    【解决方案2】:

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

    .wrapper {height: 30px;}
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-22
      • 2010-12-17
      • 2010-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多