# Tabularx table with many columns malformatted

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):

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:

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.

• Please provide an MWE! Your first table has more cells than columns. – LaRiFaRi Feb 26 '15 at 8:18
• I don't get it except lot of bad boxes. – user11232 Feb 26 '15 at 8:21
• If you use p{1cm} and 19 columns are too wide, the columns stay that width but tex makes the table too wide, if you use tabularx{\textwidth} then the table will be that wide and if the columns are not wide enough to fit in a single digit they wil be over full. – David Carlisle Feb 26 '15 at 8:24
• Rather than make people guess how you obtained that output image, every question should have a complete small document that reproduces the problem. Then people can easily debug it and test answers. Please fix the code fragment to be a complete document that produces the problem image. – David Carlisle Feb 26 '15 at 9:27

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.