A Web Design Community curated by Chris Coyier

Using Divs Inside Tables

By: Chris Coyier on 8/15/2007

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>
		<div id="my_box">
			<td colspan=3>
				<p>I'm text in a div.</p>
			</td>
		</div>
	</tr>

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

tablediv3.png

One Response

  1. Philippe says:

    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?

This comment thread is closed. If you have important information to share, you can always contact me.

* This website may or may not contain any actual CSS or Tricks.