# Misplaced \noalign when centering tabularx cell

I have a minimal LaTeX document like this:

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


I would like to center the table headers but left-align the columns. However, when I add \centering to the B header, like this:

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


I get this error:

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

! Extra alignment tab has been changed to \cr.

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.

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.

l.8   \end{tabularx}


Page 2 of the tabularx documentation says that you have to use \arraybackslash after \centering (or \raggedright or \ragggedleft). Use like this:

\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's text alignment commands redefine \\ so that they don't mean “a new line in the table” anymore. The \arraybackslash command does \let\\\tabularnewline so that it will work again.

You can simply use a \multicolumn{1}{c}{...} for the column heads. Or load makecell and use its thead command (by default, its content is centred, both horizontally and vertically), which has the possibility to define a common formatting of all theads arguments. Here is an example of both methods:

\documentclass{article}
\usepackage{tabularx, makecell, xcolor}

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