Using Divs Inside Tables

Avatar of Chris Coyier
Chris Coyier on (Updated on )

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

Despite their status as mortal enemies, divs and tables can work together if you need them to. Because of the ability to use vertical centering in tables, it is a somewhat popular technique to use a single-celled table with both horizontal and vertical centering to absolutely center your page content in a browser window (mostly only useful for fixed-size content).

One important thing to remember when putting a div inside of a table is that the div needs to live inside of a particular table cell, meaning inside of a td or th element which is inside of a tr element.

To see what I mean, take a look at a table like this:

<table border=1 width=200 cellpadding=10>
  <tr>
    <td>
      <p>I'm text in a cell.</p>
    </td>
    <td>
      <p>I'm text in a cell.</p>
    </td>
    <td>
      <p>I'm text in a cell.</p>
    </td>
  </tr>
  <tr>
    <td>
      <p>I'm text in a cell.</p>
    </td>
    <td>
      <p>I'm text in a cell.</p>
    </td>
    <td>
      <p>I'm text in a cell.</p>
    </td>
  </tr>
</table>

tablediv1.png

Now you want to add another row to this table and put a div inside it, you might do this:

<table border=1 width=200 cellpadding=10>
  <tr>
    <td>
      <p>I'm text in a cell.</p>
    </td>
    <td>
      <p>I'm text in a cell.</p>
    </td>
    <td>
      <p>I'm text in a cell.</p>
    </td>
  </tr>
  <tr>
    <td>
      <p>I'm text in a cell.</p>
    </td>
    <td>
      <p>I'm text in a cell.</p>
    </td>
    <td>
      <p>I'm text in a cell.</p>
    </td>
  </tr>
  <tr>
    <div id="my_box">
      <p>I'm text in a div.</p>
    </div>
  </tr>
</table>

But that breaks the layout! Strange but true. See below:

tablediv2.png

What you need to do is make sure the div is inside an actual table cell, a td or th element, so do that:

<tr>
  <td colspan=3>
    <div id="my_box">
      <p>I'm text in a div.</p>
    </div>
  </td>
</tr>

And you should get what you are expecting, a fully style-able div inside a table:

tablediv3.png

This can help with using absolute positioning inside of table cells as well. See this article.