Fix your tables: how to stop cells from expanding out of control
HTML tables receive a bit of a bad rap thanks to years of abuse in web design, however in reality they're semantic as the next element. They do have their quirks though, one common problem is that instead of aligning themselves like the rigid blocks
we're used to they tend to be a bit more fluid - expanding and contracting to fit their content.
This useful behaviour can become frustrating when a carefully laid-out table encounters abnormal input and suddenly decides to stop paying attention to the cell widths we've specified. Luckily there is a simple solution to this. All the major browsers implement an alternative fixed
table layout which is specified through the appropriately named table-layout
CSS property.
The demo table below should be 200 pixels wide, with each column taking up 50% of the total width. With the default layout enabled the last word clearly pushes the table beyond these dimensions. You can toggle the table-layout
between fixed
and auto
(the default) to see the differences.
Top 5 Words
Word | Frequency |
---|---|
Bite | 5,631 |
My | 6,405 |
Shiny | 7,435 |
Metal | 8,682 |
Rindfleischetikettierungsüberwachungsaufgabenübertragungsgesetz | 109,392 |
On a related node, you'll notice that overflow: hidden
has no effect on table cells. You'll have to wrap the cell contents in a container element if you want to crop it.
This simple CSS property tends to go a unnoticed, but when you need it you'll definitely be thankful it's there.