[Tex/LaTex] Tables with centered columns of specific width

tables

I like it when tables have centered columns (e.g. |c|c|c|).

However, I have width restrictions. The most obvious solution to force a table to be within a certain width is to do |p{2.5cm}|p{2.5cm}|, etc. However, this puts the text off to one side instead of centered.

Ideally, I'd like to say "my table will be a total of 10cm wide" and "the columns will be centered." Is there a way to do this?

Next best thing, can I make a table where I specify each column's width, and the columns are centered?

Best Answer

There are two ways you can achieve what you want. The first is as in Maarten's answer, which requires you to specify the width of each column. The use of \arraybackslash is needed in case the centred column is the last column in the table. See the array package documentation for more information on this or Difference between \\ and \tabularnewline.

A second way is to use the tabulary package, which allows you to define columns that will fill up the maximum width of the table. Here's an example of both. I've used K as the column type to distinguish it from the C column type defined within the tabulary environment.

Please note that I've used \hline in the example code just to show the width of the tables. For most tables I would highly recommend the booktabs package, and its various rule commands which have much better spacing and width parameters.

\documentclass{article}
\usepackage{array}
\usepackage{tabulary}
\newcolumntype{K}[1]{>{\centering\arraybackslash}p{#1}}
\begin{document}
table with centred columns of specified width
\bigskip

\begin{tabular}{K{2cm}K{2cm}}
\hline
foo & bar \\
foobar & barfoo \\
\hline
\end{tabular}
\bigskip

table of 5cm width, centred columns
\bigskip

\begin{tabulary}{5cm}{CC}
\hline
foo & bar \\
foobar & barfoo\\
A much wider column  & c \\
\hline
\end{tabulary}
\bigskip

as we make the total width wider, the columns adjust
\bigskip

\begin{tabulary}{8cm}{CC}
\hline
foo & bar \\
foobar & barfoo\\
A much wider column  & c \\
\hline
\end{tabulary}
\end{document}

output of code