2014-11-25 166 views
4

当我尝试绝对定位表格单元格内的div元素时,我遇到了一个奇怪的行为。为了实现绝对定位,我用position:relative包装div元素:CSS:表格单元格中绝对位置的神秘填充

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,此间隔将消失。

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

回答

4

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

它位于单元格的垂直中间位置,因为middletdth s的默认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>

+0

谢谢,这几乎回答了这个问题,它的小提琴之内解决问题。不幸的是,它并没有解决我的实际问题。我认为小提琴会很好地重现它,但显然它不会。但无论如何,这应该是正确的答案。 – basilikum 2014-11-25 11:06:54

+0

我很高兴我能帮上忙。你能扩展你的更大的问题吗?如果合适,也许再问一个问题? – George 2014-11-25 11:10:58

+0

是的,只要我设法在'vertical-align:top;'的小提琴中重现此问题,我可能会提出另一个问题。到目前为止,我仍然无法做到这一点。 – basilikum 2014-11-25 12:28:57

1

你必须设置尺寸为包装,

.wrapper {height: 30px;} 

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

否则,.wrapper高度为0,表格单元格在默认情况下有vertical-align: middle;,所以蓝色边框是在小区的中间。