![居中 tabularx 单元格时 \noalign 位置错误](https://linux22.com/image/390900/%E5%B1%85%E4%B8%AD%20tabularx%20%E5%8D%95%E5%85%83%E6%A0%BC%E6%97%B6%20%5Cnoalign%20%E4%BD%8D%E7%BD%AE%E9%94%99%E8%AF%AF.png)
我有一个像这样的最小 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}
我想将表头居中,但将列左对齐。但是,当我添加\centering
B 标题时,如下所示:
\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
说您必须使用\arraybackslash
after \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
命令(默认情况下,其内容在水平和垂直方向上均居中),这可以定义所有thead
s 参数的通用格式。以下是两种方法的示例:
\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}