我尝试创建一个带有居中标题且包含换行符的表格。不幸的是,标题内的文本未正确居中。我做错了什么?
梅威瑟:
\documentclass[a4paper,11pt]{scrbook}
\usepackage[utf8]{inputenc}
\usepackage{array}
\usepackage{booktabs}
\begin{document}
\begin{table}[htbp]
\caption{My own test table.}
\begin{center}
\begin{tabular}{l
>{\raggedright\arraybackslash}p{.27\textwidth}
>{\raggedright\arraybackslash}p{.27\textwidth}
>{\raggedright\arraybackslash}p{.27\textwidth}}
\toprule &
\multicolumn{1}{>{\centering}p{.27\textwidth}}{AAA AAA \newline AAA} &
\multicolumn{1}{>{\centering}p{.27\textwidth}}{BBB BBB \newline BBB} &
\multicolumn{1}{>{\centering}p{.27\textwidth}}{CCC CCC \newline CCC} \\ \midrule
\emph{Blah} &
test
&
test
&
test \\ \bottomrule
\end{tabular}
\end{center}
\end{table}
\end{document}
附言:是的,我确实需要在表格标题中添加这个换行符。当然,真正的表格要复杂得多。
答案1
使用makecell
包很简单:
\documentclass[a4paper,11pt]{scrbook}
\usepackage[utf8]{inputenc}
\usepackage{array,makecell}% <-- added makecell
\usepackage{booktabs}
\begin{document}
\begin{table}[htbp]
\caption{My own test table.}
\begin{center}
\begin{tabular}{l
>{\raggedright\arraybackslash}p{.27\textwidth}
>{\raggedright\arraybackslash}p{.27\textwidth}
>{\raggedright\arraybackslash}p{.27\textwidth}}
\toprule &
\thead{AAA AAA \\ AAA} &
\thead{BBB BBB \\ BBB} &
\thead{CCC CCC \\ CCC} \\ \midrule
\emph{Blah} &
test
&
test
&
test \\ \bottomrule
\end{tabular}
\end{center}
\end{table}
附录: 另一种解决方案是将换行符留在列类型中(正如您在 MWE 中所做的那样):
\documentclass[a4paper,11pt]{scrbook}
\usepackage[utf8]{inputenc}
\usepackage{array}
\usepackage{booktabs}
\newcolumntype{C}[1]{>{\centering\arraybackslash}p{#1}}
\newcolumntype{L}[1]{>{\raggedright\arraybackslash}p{#1}}
\begin{document}
\begin{table}[htbp]
\caption{My own test table.}
\begin{center}
\begin{tabular}{l L{.27\textwidth}
L{.27\textwidth}
L{.27\textwidth}} \\
\toprule &
\multicolumn{1}{C{.27\textwidth}}{AAA AAA AAA AAA AAA AAA AAA} &
\multicolumn{1}{C{.27\textwidth}}{BBB BBB\par BBB} &
\multicolumn{1}{C{.27\textwidth}}{CCC CCC CCC CCC CCC} \\ \midrule
\emph{Blah} &
test
&
test
&
test \\ \bottomrule
\end{tabular}
\end{center}
\end{table}
在居中文本的列中使用\newline
效果不佳。相反,最好使用\par
如上图所示的 MWE。