[Tex/LaTex] Tabularx table with many columns malformatted

tabularx

In our software we have a module, that generates PDFs via Latex. Some of them contain tables and I want them to span the whole page. Since the number of columns varies, I use tabularx with all X columns and it does the job.

However, in the rare case that a table has many columns (it seems 19 is the threshold), they wind up malformatted.

This is fine:

\begin{tabularx}{\textwidth}{|X|X|X|X|X|X|X|X|X|X|X|X|X|X|X|X|X|X|X|}
0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 & 16 & 17 & 18 \\
\end{tabularx}

Output (as expected):

enter image description here

If I add one more column, it breaks:

\begin{tabularx}{\textwidth}{|X|X|X|X|X|X|X|X|X|X|X|X|X|X|X|X|X|X|X|X|}
0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 & 16 & 17 & 18 & 19\\
\end{tabularx}

Output:

enter image description here

I can work around this, by using p{1cm} instead of X after the 18th column or so. Since the table is already that huge it does not distort the layout too much.
But I would still like to understand what causes this and if other solutions exist.

Best Answer

Just a bit of math, assuming the standard text width of article (345pt), the standard \tabcolsep (6pt) and the standard rule width (0.4pt).

With 19 columns you have to do (345-38*6-20*0.4)/19 = 5.73684 (rounded), so you have just 5.73684pt width for the X columns and each digit is about 5pt. Indeed, for this case I get

Overfull \hbox (4.26317pt too wide)

and 10-5.73684=4.26316 (being off by one in the fifth decimal digit is normal).

So if you want to ensure 20 columns with two digit entries will fit, you need to adjust the parameters; you need

20 * 10 + 20 * 2 * \tabcolsep + 21 * 0.4

Reducing \tabcolsep to 3pt, say, this amounts to 328.4pt, that fits:

\documentclass{article}
\usepackage{tabularx}

\begin{document}

\setlength{\tabcolsep}{3pt}
\noindent
\begin{tabularx}{\textwidth}{|X|X|X|X|X|X|X|X|X|X|X|X|X|X|X|X|X|X|X|X|}
0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 & 16 & 17 & 18 & 19\\
\end{tabularx}

\end{document}

This compiles without any warning.

enter image description here

Related Question