如何在表格中居中某些行但不居中其他行

如何在表格中居中某些行但不居中其他行

我有代码

 \begin{center}
    \begin{tabular}{p{0.4\linewidth}p{0.4\linewidth}}
        \toprule
        \multicolumn{1}{c}{column 1} & \multicolumn{1}{c}{column 2} \\ \midrule
        should be centered &  should be centered\\
        should be centered & should be centered\\
        \\
        Should be left aligned
        & 
        Should be left aligned\\
        \bottomrule
    \end{tabular}
\end{center}

这给了我下表

在此处输入图片描述

如何使某些线居中,而其他线不居中?

答案1

一个非常简单的方法是重复你在第一行所做的操作。或者,由于居中行比左对齐行多,你也可以只\multicolumn对左对齐行使用。

\documentclass{article}
\usepackage{booktabs}
\begin{document}
\begin{center}
    \begin{tabular}{p{0.4\linewidth}p{0.4\linewidth}}
        \toprule
        \multicolumn{1}{c}{column 1} & \multicolumn{1}{c}{column 2} \\ \midrule
        \multicolumn{1}{c}{should be centered} &  \multicolumn{1}{c}{should be
        centered}\\
        \multicolumn{1}{c}{should be centered} & \multicolumn{1}{c}{should be
        centered}\\
        \\
        Should be left aligned
        & 
        Should be left aligned\\
        \bottomrule
    \end{tabular}
\end{center}
\begin{center}
    \begin{tabular}{cc}
        \toprule
        column 1 & column 2 \\ \midrule
        should be centered &  should be
        centered\\
        should be centered & should be
        centered\\
        \\
        \multicolumn{1}{p{0.4\linewidth}}{Should be left aligned}
        & 
        \multicolumn{1}{p{0.4\linewidth}}{Should be left aligned}\\
        \bottomrule
    \end{tabular}
\end{center}
\end{document}

在此处输入图片描述

答案2

我假设由于您p对两个主列都使用了列类型,因此无论行是左对齐还是居中,都应该允许自动换行。以下解决方案实现了此格式化目标。

请注意,在列类型\RaggedRight定义中使用的指令L会引发左对齐(同时仍允许使用连字符,如果需要)。相比之下,基本p列类型执行完全对齐,不是左对齐。

在此处输入图片描述

\documentclass{article}
\usepackage{booktabs,array,ragged2e}
% define 2 column types that perform centering and left-alignment, resp.
\newcolumntype{C}[1]{>{\Centering\arraybackslash}p{#1\linewidth}}
\newcolumntype{L}[1]{>{\RaggedRight\arraybackslash}p{#1\linewidth}}
\newcommand\mC[2]{\multicolumn{1}{C{#1}}{#2}} % handy shortcut macro

\begin{document}
\begin{center}
    \begin{tabular}{L{0.4}L{0.4}}
      \toprule
      \multicolumn{1}{c}{Column 1} & \multicolumn{1}{c}{Column 2} \\ 
      \midrule
      \mC{0.4}{Should be centered while allowing line breaks} & 
      \mC{0.4}{Should be centered while allowing line breaks}\\
      \mC{0.4}{Should be centered while allowing line breaks} & 
      \mC{0.4}{Should be centered while allowing line breaks}\\
      \\
      Should be left-aligned while allowing line breaks & 
      Should be left-aligned while allowing line breaks\\
    \bottomrule
  \end{tabular}
\end{center}
\end{document}

相关内容