居中 tabularx 单元格时 \noalign 位置错误

居中 tabularx 单元格时 \noalign 位置错误

我有一个像这样的最小 LaTeX 文档:

\documentclass{article}
\usepackage{tabularx}
\begin{document}
  \noindent
  \begin{tabularx}{\linewidth}{ X | X }
    \centering A & B \\ \hline
    1.0 & 2.0 \\
  \end{tabularx}
\end{document}

AB 1.0 2.0

我想将表头居中,但将列左对齐。但是,当我添加\centeringB 标题时,如下所示:

\documentclass{article}
\usepackage{tabularx}
\begin{document}
  \noindent
  \begin{tabularx}{\linewidth}{ X | X }
    \centering A & \centering B \\ \hline
    1.0 & 2.0 \\
  \end{tabularx}
\end{document}

我收到此错误:

! Misplaced \noalign.
\hline ->\noalign
                  {\ifnum 0=`}\fi \hrule \@height \arrayrulewidth \futurelet...
l.8   \end{tabularx}

! Extra alignment tab has been changed to \cr.
<recently read> \endtemplate

l.8   \end{tabularx}

! Misplaced \noalign.
\hline ->\noalign
                  {\ifnum 0=`}\fi \hrule \@height \arrayrulewidth \futurelet...
l.8   \end{tabularx}

! Extra alignment tab has been changed to \cr.
<recently read> \endtemplate

l.8   \end{tabularx}

! Misplaced \noalign.
\hline ->\noalign
                  {\ifnum 0=`}\fi \hrule \@height \arrayrulewidth \futurelet...
l.8   \end{tabularx}

! Extra alignment tab has been changed to \cr.
<recently read> \endtemplate

l.8   \end{tabularx}

答案1

文档的第 2 页tabularx说您必须使用\arraybackslashafter \centering(或\raggedright\ragggedleft)。像这样使用:

\documentclass{article}
\usepackage{tabularx}
\begin{document}
  \noindent
  \begin{tabularx}{\linewidth}{ X | X }
    \centering\arraybackslash A & \centering\arraybackslash B \\ \hline
    1.0 & 2.0 \\
  \end{tabularx}
\end{document}

LaTeX 的文本对齐命令重新定义\\,使其不再表示“表格中的新行”。该\arraybackslash命令\let\\\tabularnewline这样做是为了使其再次起作用。

或者,您可以在第一行末尾使用\tabularnewline而不是。\\

\documentclass{article}
\usepackage{tabularx}
\begin{document}
  \noindent
  \begin{tabularx}{\linewidth}{ X | X }
    \centering A & \centering B \tabularnewline \hline
    1.0 & 2.0 \\
  \end{tabularx}
\end{document}

答案2

您可以简单地使用 a\multicolumn{1}{c}{...}作为列标题。或者加载makecell并使用其thead命令(默认情况下,其内容在水平和垂直方向上均居中),这可以定义所有theads 参数的通用格式。以下是两种方法的示例:

\documentclass{article}
\usepackage{tabularx, makecell, xcolor}
\renewcommand{\theadfont}{\normalsize\bfseries\color{red}}

\begin{document}

  \noindent
  \begin{tabularx}{\linewidth}{ X | X }
    \multicolumn{1}{c}{A} & \multicolumn{1}{c}{B} \\ \hline
    1.0 & 2.0 \\
  \end{tabularx}
\vspace{4ex}

  \noindent
  \begin{tabularx}{\linewidth}{ X | X }
    \thead{A} & \thead{B} \\ \hline
    1.0 & 2.0 \\
  \end{tabularx}

\end{document} 

在此处输入图片描述

相关内容