Reputation: 10536
I'm experiencing a weird behaviour when trying to absolute position a div element inside a table-cell. To realise absolute positioning, I use a wrapper div element with position:relative
:
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;
}
As you can see, there is a gap between the wrapper div and the top of the containing table-cell. This gap will vanish if I change the abs
element to position:relative
.
So where does this gap come from and how do I prevent it?
Upvotes: 4
Views: 527
Reputation: 36794
Since you take .abs
out of the normal page flow, .wrapper
no longer has any content, so it collapses on itself and all you see is the border along the top of it.
It is in the vertical-middle of the cell because middle
is the default vertical-align
style for td
and th
s.
This can be better demonstrated if we add a non-breaking space in the mix:
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">
<div class="abs">abs</div>
</div>
</td>
<td>Content 2</td>
</tr>
</tbody>
</table>
Upvotes: 4
Reputation: 27092
You have to set dimensions to wrapper,
.wrapper {height: 30px;}
http://jsfiddle.net/b1j2gbn3/2/
Else, the .wrapper
height is 0 and table cell has vertical-align: middle;
by default, so the blue border is in the middle of the cell.
Upvotes: 1