I need to position something with absolute positioning inside a td. To get around the fact that a td is undefined when setting it to relative, I use a div set to relative inside my td then inside that div I have an inner div set to absolute. This all works great when I have content filling up the td. When I set the content of the td to display none then the absolute positioning gets all screwed up.
Does anyone know why this would be.
HTML:
<table>
<tr>
<td>
<div class="relative">
<div class='absolute'>
<p>A</p>
</div>
</div>
<div class="slot"></div>
<div class="slot"></div>
</td>
<td>
<div class="relative">
<div class='absolute'>
<p>B</p>
</div>
</div>
<div class="slot hidden"></div>
<div class="slot"></div>
</td>
</tr>
</table>
And CSS:
td{
border:1px solid red;
width:100px;
height:60px;
vertical-align:bottom;
}
.slot{
width:100px;
height:29px;
background-color:#999;
border:1px dashed blue;
}
.relative{
position:relative;
}
.absolute{
position:absolute;
top:5px;
left:5px;
}
.hidden{
display:none;
}
And a live version: http://jsfiddle.net/HgEtQ/
In the fiddle above you can see the first table cell works correctly. The absolutely positioned div is in the correct space. The second one has hidden the top slot and now the absolute positioning is not in the top left corner anymore. If you take out both slots then it really screws up the absolute positioning. I need to positioning it absolute because some of the elements will be shifted depending on the element.
There are a couple things going on here.
You have this:
That will push the content of the cells to the bottom.
Also, an absolutely positioned element is removed from the normal flow so it won’t contribute to its parent’s height:
In particular, this means that your
div.relativeelements have a height of zero but they will still have an upper left corner so your absolute positioning offsets are anchored somewhere.Then you have
<div class="slot hidden">and thehiddenremoves the<div>from the layout so you effectively have just this:That combined with the
vertical-align: bottommeans that your seconddiv.absolutewill be positioned 5px from the top of thediv.slotand that is 25px from the bottom of the table cell.The first cell works fine because the two visible
div.slotelements push thediv.relativeright to the top of the cell, then thediv.absoluteis positioned 5px from the top of thediv.relativeand that is 5px from the top of the table cell.Unfortunately, adding
position: relativeto a<td>is a bit dodgy as far as browsers go so you’ll need some hackery to get your positioning right while keepingvertical-align: bottom. You could re-structure the<td>s like this:And the CSS like this:
Live example: http://jsfiddle.net/ambiguous/aV4nT/
Or you could use
visibility: hidden:instead of
display: nonefor your.hiddenclass:This will leave both
div.slotelements taking up space and affecting the layout but only the second one will be seen.Live example: http://jsfiddle.net/ambiguous/RcdNh/