12

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?

12

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

6

Add a multicolumn that spans no columns.

\documentclass[12pt,a4paper]{book}

\def\x{This is a text aligned according to column alignment defined in tablular.}
\def\y{Centered text}

\begin{document}

\begin{tabular}{l|l}
   \x & \x \\
   \x & \x \\
   \multicolumn{1}{c}{\y} & \x 
\end{tabular}

\endtabular}

\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.