/blog/articles/

Use position relative & absolute in tables

Given that the days of building layouts with tables are long gone, we don't have to use tables that often in our day to day developer lives. Or at least that's the case for me. (Hang in there HTML e-mail builders. I feel you.)

This means if I have to build a complex table it can get somewhat confusing from time to time. Recently I needed to position an element absolute inside a table cell.

As it turns out, table cells don't like to be position relative to serve as a point of reference for the absolute positioned element inside it. Here is a little trick (or call it hack if you want to), to use position relative on a table cell and thus position elements absolute inside of it.

What you need to do is put a helper div inside your td which gets all the styling that you normally would have applied to your td, like padding or a background-color for example. This div will mimic your table cell and can get position: relative;

And here is how the code looks like as well as an not very good looking example on CodePen.

This is the HTML for our little hack to work:

<table cellpadding="0" cellspacing="0" border="0">
  <tr>
    <td>
      <div>my content <span class="my-absolute-class">x</span></div>
    </td>
    <td>
      <div>more content</div>
    </td>
  <tr>
</table>

And the corresponding CSS to make it complete:

table {
  width: 300px;
  border: 1px solid #ccc;
  border-right: 0;
}

td > div {
  position: relative;
  padding: 10px;
  border-right: 1px solid #ccc;
}

.my-absolute-class {
  position: absolute;
  top: 5px;
  right: 5px;
  padding: 0px 3px;
  color: #fff;
  background: #000;
}

See the Pen Position relative/absolute in tables by Martin Wolf (@martinwolf) on CodePen.

Update

It's pointed out to me on Twitter by @niksy, that this solution fails if you are dealing with multiline cells. As far as I can see, the only solution to this problem is to use Javascript to set the height of the helper div as tall as the td — on load and on resize if the height of the td changes in a responsive environment.

Martin Wolf

Hi, I’m Martin Wolf, a Freelance Frontend Web Developer from Germany.
I believe in hard work and sharing what I know.

Contact me

Interested in working with me? Fantastic! The best way to get in touch is by email (hello@martinwolf.org). I’m looking forward to hearing from you.