Consider the following hunk of code:
\begin{tabular}{| c | c | c | c | c | c | c | }
\cline{2-7}
\multicolumn{1}{c}{} & \multicolumn{3}{|c|}{Fantastical aardvarks}
& \multicolumn{3}{c|}{Spelunking elephants}\\
\hline
Foo bar & A & B & C & A & B & C\\
\hline
5 & 87 & 5 & 2 & 82 & 18 & 48\\
6 & 5 & 43 & 4 & 7 & 47 & 4\\
7 & 7 & 18 & 63 & 2 & 9 & 99\\
\hline
\end{tabular}
Is there a way to have the three columns under "Fantastical aardvarks" and, separately, under "Spelunking elephants" have widths that are evenly distributed?
I'm particularly interested in an automated way of doing this, without needing to directly specify column widths.
Best Answer
You could use the
tabularx
environment instead of thetabular
environment. Thetabularx
environment, made available by loading the tabularx package, provides a column type called "X" that should satisfy your professed need to have several equal-width columns. The first table in the MWE below explains how to do this.There is one decision, however, that the author must make, i.e., which can't be automated entirely: How wide should the entire table be? Often, one simply sets this width to
\textwidth
(the width of the current textblock) and then letstabularx
determine how wide the individual columns of typeX
will be. For this MWE (which uses the default text font employed by LaTeX), with some trial-and-error work I found that it's possible to specify the table's overall width as narrow as about0.75\textwidth
. For your actual document, you will need to play around with the table width settings to determine empirically what the narrowest possible table width may be.Note also the use of the specifier
\centering\arraybackslash
before theX
column type in the MWE. I've inserted this specifier as it appears that you want the contents of the columns to be centered. (The contents of anX
column are set "fully justified" by default.)That said, I'd also like to very strongly encourage you to consider (i) getting rid of all vertical lines in the table and (ii) using the booktabs package to getter spacing above and below the various rules in the table. This package provides the commands
\toprule
,\bottomrule
,\midrule
, and\cmidrule
; how to use them is explained in the second part of the MWE below. Note that it's possible to left-trim and/or right-trim a\cmidrule
-- something that's quite impossible to achieve with\cline
. Comparing the two forms of the table, I daresay predict that the overwhelming majority of readers will find the second form to be both more pleasing to look at and more easily understandable. :-)