[Tex/LaTex] Center text in a single table cell

horizontal alignmenttables

Suppose I have simple table. While I want the columns in general to be flush both right and left, there are certain cells that I want to be centered.

\documentclass[12pt,a4paper]{book}

\def\x{This is a paragraph of text that should be flush both right and left. Centering an adjacent cell should not cause this cell to be centered.}
\def\y{Centered text}

\begin{document}
\centering
\begin{tabular}{p{2in}|p{2in}}
\x & \y \\
\y & \x \\
\x & \x
\end{tabular}

\end{document}

This has the output that I expected.

enter image description here

But what do I do when I want to center the cells that say "Centered text"? I tried to do it with the \centering command,

\def\y{\centering Centered text}

but it comes up with the following error:

! Extra alignment tab has been changed to \cr.

How can I center individual cells?

Best Answer

The error occurs because \\ is redefined by \centering (and other commands, such as \raggedright), but the problem only occurs for the final column. To fix it you can load the array package and add \arraybackslash after \centering in the cell, which restores the definition of \\.

Another option, mentioned by Gonzalo Medina in a comment, is to use \tabularnewline instead of \\ to end the row, which does not require array:

\x & \centering\y \tabularnewline

(The \arraybackslash command is simply defined as \def\arraybackslash{\let\\\tabularnewline})

Complete example:

\documentclass[12pt,a4paper]{book}
\usepackage{array}

\def\x{This is a paragraph of text that should be flush both right and left. Centering an adjacent cell should not cause this cell to be centered.}
\def\y{Centered text}

\begin{document}
\centering
\begin{tabular}{p{2in}|p{2in}}
\x & \centering\arraybackslash\y \\
% \x & \centering\y \tabularnewline  % alternative version of the previous line
\centering\y & \x \\
\x & \x
\end{tabular}

\end{document}

enter image description here

Related Question