reprogrammer
reprogrammer

Reputation: 14728

How to center cell contents of a LaTeX table whose columns have fixed widths?

Consider the following piece of LaTeX code:

\begin{tabular}{p{1in}p{1in}} 
A & B\\ 
C & D\\
\end{tabular}

How can I make the contents of each cell aligned in the center of the cell rather than the left? Note that I want to make sure that the widths of my columns are fixed, so I cannot use the "c" position attribute instead of "p{.1in}" to center my cell contents.

Upvotes: 78

Views: 203777

Answers (3)

MattAllegro
MattAllegro

Reputation: 7365

I think that this answer is the best source. You can declare the newcolumntype in the header and then use it when necessary:

\documentclass{article}
\usepackage{array}

\newcolumntype{C}[1]{>{\centering\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}

\begin{document}
\begin{tabular}{|C{1in}|C{1in}|}
A & B\\
C & D\\
\end{tabular}
\end{document}

I only added the vertical lines | to make the column width (1in) and the centering more evident in the output:

screenshot of output

Upvotes: 1

Mica
Mica

Reputation: 19637

\usepackage{array} in the preamble

then this:

\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}

note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"

Upvotes: 109

Matt Ball
Matt Ball

Reputation: 359966

You can use \centering with your parbox to do this.

More info here and here.

(Sorry for the Google cached link; the original one I had doesn't work anymore.)

Upvotes: 8

Related Questions