Grow your CSS skills. Land your dream job.

Using Divs Inside Tables

Published by Chris Coyier

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 element which is inside of a tr or th 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.

Comments

  1. Permalink to comment#

    In your last example, you demonstrated that the div should live inside a td, which is contained in the tr. However, your last code sample shows the opposite; a td inside a div, inside a tr. Is your sample correct?

    Editors note: This is fixed.

Leave a Comment

Current day month ye@r *

*May or may not contain any actual "CSS" or "Tricks".