Problems positioning an absolut element in a relative <td>

HI, I’m having difficulty with absolutely positioned elements within a table.

my td is relative, so according to what I read, the absolutely positioned element within should be positioned with respect to the td cell… but intstead, as seen form the code below, the absolutely positioned element (in this case h2) is positioned in the top left.

“An absolute position element is positioned relative to the first parent element that has a position other than static. If no such element is found, the containing block is <html>”

in the code below, the containing block for my <h2> is (I think… from how it appeasrs) <html>… why isn’t it <td> since the td has relative position?

<html>
<head>
<style type="text/css">
td {
position: relative;
}
 
h2 {
position:absolute;
left:0px;
top: 0px;
}
</style>
</head>
 
<body>
<table><tr>
<td>I am in the first cell of the table.</td>
<td><h2>I am in the second cell.</h2></td>
</tr></table>
</body>
</html>

Thanks!

Hi galneweinhaw, welcome to SitePoint! :wave:

Table cells are not reliable to create the stacking context needed to containing AP children. I suggest you e.g. wraps the text inside the H2 in a span and position the span relative the H2 instead.

td h2{
  position:relative;
}
 
td h2 span{
  position:absolute;
  left:0;
  top:0;
}




<td><h2><span>I am in the second cell.</span></h2></td>

That is true but not for table-cells unfortunately :slight_smile:

Quote from the Sitepoint reference:

relativeThe value relative generates a positioned box whose position is first computed as for the normal flow. The generated box is then offset from this position according to the properties top or [URL=“http://reference.sitepoint.com/css/bottom”]bottom and/or [URL=“http://reference.sitepoint.com/css/left”]left or [URL=“http://reference.sitepoint.com/css/right”]right. The position of the following box is computed as if the relatively positioned box occupied the position that was computed before the box was offset. This value cannot be used for table cells, columns, column groups, rows, row groups, or captions.

The W3c specs state:

The effect of ‘position:relative’ on table-row-group, table-header-group, table-footer-group, table-row, table-column-group, table-column, table-cell, and table-caption elements is undefined.

In effect this means that you cannot use position:relative on table cells and would need to do as Erik suggests above.

Thanks a ton for your help!

I was wrapping the position element in a container div with position relative to get it to work, but it was frusterating not understanding why it just wouldn’t work with td.

Thanks very much for the sitepoint reference So much more thorough than the one I was using!