Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Taming table column widths
/**
* Taming table column widths
*/
body { background: #ddd }
section {
width: 500px;
margin: 2em;
background: white;
}
table {
border-collapse: collapse;
margin-bottom: 1em;
width: 100%;
}
section + section table { table-layout: fixed }
td {
border: 1px solid #aaa;
}
td.preformatted {
white-space: pre;
font-family: Consolas, Monaco, monospace;
text-overflow: ellipsis;
overflow: hidden;
}
<section>
<h1>With table-layout: auto</h1>
<div>
<table>
<tr>
<td>If we don’t…</td>
<td>specify a cell width, they will be assigned one that depends on their contents. Notice how the cell with the more content here is much wider.</td>
</tr>
</table>
<table>
<tr>
<td>If we don’t…</td>
<td>specify a cell width, they will be assigned one that depends on their contents. Notice how the cell with the more content here is much wider.</td>
</tr>
<tr>
<td>All rows take part in calculating the widths, not just the first one.</td>
<td>Notice how the dimensions here are different than the previous example.</td>
</tr>
</table>
<table>
<tr>
<td style="width: 1000px">If we specify a width, it will not always be followed. I have a width of <code>1000px</code>…</td>
<td style="width: 2000px">…and I have a width of <code>2000px</code>. Because there’s not enough space for <code>3000px</code>, they are reduced proportionally, to 33.3% and 66.6% of the total width.</td>
</tr>
</table>
<table>
<tr>
<td>If we prevent word wrapping, the table can become so wide it grows beyond its container.</td>
<td class="preformatted">…and <code>text-overflow: ellipsis</code> doesn’t help either.</td>
</tr>
</table>
<table>
<tr>
<td>Large images and blocks of code can also cause the same issue.</td>
<td><img src="http://lea.verou.me/book/panoramic.jpg" /></td>
</tr>
</table>
</div>
</section>
<section>
<h1>With table-layout: fixed</h1>
<div></div>
</section>
document.querySelector('section + section div').innerHTML = document.querySelector('section:first-of-type div').innerHTML;
{"view":"split-vertical","fontsize":"100","seethrough":"","prefixfree":"1","page":"css"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.