📐 CSS table-layout
— Controlling Table Column Behavior
Tables in HTML can automatically size their columns based on content. But if you need consistent layouts and performance, CSS gives you the table-layout
property to control how column widths are calculated.
🔹 What is table-layout
?
The table-layout
property defines how the width of a table and its columns is determined.
It only applies to HTML tables (with display: table
, table-row
, or table-cell
).
📘 Syntax
table {
table-layout: auto | fixed | inherit;
}
🔄 Values Explained
Value | Description |
---|---|
auto | Default. Column widths adjust based on content. Slower but flexible. |
fixed | Column widths are based on the first row or set by CSS. Faster rendering. |
inherit | Inherits the value from its parent element. |
✍️ Example: auto
vs fixed
HTML:
<table class="auto-table">
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr>
<td>Cat</td>
<td>Small domesticated carnivorous mammal</td>
</tr>
</table>
CSS:
.auto-table {
width: 100%;
table-layout: auto;
border: 1px solid #ccc;
}
Behavior:
- The second column stretches to fit the long description.
- Table layout adapts based on content.
Now with table-layout: fixed
:
.fixed-table {
width: 100%;
table-layout: fixed;
}
- All columns share available space evenly or follow set widths.
- Content may overflow or wrap if it’s too wide.
🖼️ Image Idea: Auto vs Fixed Comparison
Description:
- Two side-by-side tables:
- Left:
table-layout: auto
with one wide column. - Right:
table-layout: fixed
with evenly spaced columns.
- Left:
🎯 Purpose: Clearly shows how column widths are calculated differently.
✅ Best Use Cases
Scenario | Use auto or fixed ? |
---|---|
Dynamic content sizes | auto |
Consistent table width (e.g. invoices) | fixed |
Performance-sensitive large tables | fixed |
Controlling column layout via CSS | fixed + width |
🔒 With fixed
, Use CSS Widths
.fixed-table th:first-child {
width: 150px;
}
- When using
table-layout: fixed
, CSSwidth
properties actually control layout. - No waiting for content to load before layout is calculated.
⚠️ Overflow Behavior
With table-layout: fixed
, long text might overflow or wrap depending on your white-space
setting:
td {
white-space: nowrap; /* prevents text wrapping */
overflow: hidden;
text-overflow: ellipsis;
}
🧠 Performance Tip
table-layout: fixed
improves rendering speed because the browser doesn’t need to read all table content before calculating layout.
✅ Summary
Property | table-layout |
---|---|
Default Value | auto |
Common Values | auto , fixed |
Works On | <table> elements |
Use fixed for | Faster rendering, consistent layout |
Use auto for | Content-driven flexible layouts |
🔚 Final Thought
CSS table-layout
is a powerful but underused tool that lets you take full control over how your tables behave — whether you want them to be flexible or fast and precise.