将文本置于单个表格单元格的中心

将文本置于单个表格单元格的中心

假设我有一个简单的表格。虽然我希望列总体上左右对齐,但我希望某些单元格居中。

\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}

这具有我所期望的输出。

在此处输入图片描述

但是,当我想将标有“居中文本”的单元格居中时,我该怎么做?我尝试使用以下命令执行此\centering操作,

\def\y{\centering Centered text}

但出现以下错误:

! Extra alignment tab has been changed to \cr.

我怎样才能使个别单元格居中?

答案1

发生错误是因为\\被 重新定义\centering(以及其他命令,例如\raggedright),但问题只发生在最后一列。要修复它,您可以加载包array并在单元格中添加\arraybackslash\centering这将恢复 的定义\\

Gonzalo Medina 在评论中提到的另一个选择是使用\tabularnewline而不是\\来结束行,这并不需要array

\x & \centering\y \tabularnewline

(该\arraybackslash命令简单定义为\def\arraybackslash{\let\\\tabularnewline}

完整示例:

\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}

在此处输入图片描述

答案2

添加跨越单列的多列。

\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}

相关内容