如何使用 tabularx 垂直(和水平)居中单元格文本?

如何使用 tabularx 垂直(和水平)居中单元格文本?

我的问题与这个问题非常相似:上一个问题 但是当我稍微改变示例(如下所示)时,我的单元格不再垂直对齐

\documentclass[12pt]{article}

\usepackage{tabularx,booktabs}

\renewcommand\tabularxcolumn[1]{m{#1}}
\newcolumntype{Z}[0]{>{\centering\let\newline\\\arraybackslash\hspace{0pt}}X}%
\newcolumntype{s}[0]{>{\centering\arraybackslash\hsize=.4\hsize}Z}%
\newcolumntype{n}[0]{>{\centering\arraybackslash\hsize=.8\hsize}Z}%


\begin{document}

\begin{table}
\begin{tabularx}{7cm}{s|Z|s|n}
& really really really long\linebreak heading 1 & very very narrow column & \\
\toprule
row 1 & 2314 & 2134 & medium medium column \\ \hline
row 1 & 2314 & 2134 & medium medium  column
\end{tabularx}
\end{table}


\end{document} 

输出

答案1

请注意,对于调整大小的X单元格,系数就像重心坐标,它们的总和必须等于列数。

另外,我管理水平规则满足垂直规则,并将所有规则(垂直和水平规则但有一个)设置为具有\midrules 的宽度,并且我简化了您的代码。

\documentclass[12pt]{article}

\usepackage{tabularx,booktabs}

\renewcommand\tabularxcolumn[1]{>{\centering\arraybackslash}m{#1}}
\newcolumntype{Z}[0]{>{\hsize=1.55\hsize}X}%
\newcolumntype{s}[0]{>{\hsize=.6\hsize}X}%
\newcolumntype{n}[0]{>{\centering\arraybackslash\hsize=1.25\hsize}X}%


\begin{document}

\begin{table}
\setlength\aboverulesep{0pt} \setlength\belowrulesep{0pt}
\setlength\extrarowheight{2pt}
\begin{tabularx}{7cm}{s!{\vrule width\lightrulewidth}Z!{\vrule width\lightrulewidth}s!{\vrule width\lightrulewidth}n}
& really really really long\linebreak heading 1 & very very narrow column & \\
\toprule
row 1 & 2314 & 2134 & medium medium column \\ \midrule
row 1 & 2314 & 2134 & medium medium column
\end{tabularx}
\end{table}

\end{document} 

在此处输入图片描述

答案2

尝试

\documentclass[12pt]{article}
\usepackage{booktabs,tabularx}

\renewcommand\tabularxcolumn[1]{m{#1}}
\newcolumntype{Z}[0]{>{\centering\arraybackslash}X}%
\newcolumntype{s}[0]{>{\hsize=.4\hsize}Z}%
\newcolumntype{n}[0]{>{\hsize=.8\hsize}Z}%

\begin{document} 
    \begin{table}
\begin{tabularx}{7cm}{s|Z|s|n}
& really really really long heading 1 & very very narrow column & \tabularnewline
    \toprule
row 1 & 2314 & 2134 & medium medium column \\ 
    \hline
row 1 & 2314 & 2134 & medium medium  column
\end{tabularx}
    \end{table}
\end{document}

此代码提供:

在此处输入图片描述

如您所见,上述代码大大简化了您的代码。省略\centering列类型定义中的所有冗余(在一个地方就足够了),并且省略了对和的重新定义\arraybackslash\hspace{0pt}这似乎是导致您出现问题的原因之一(第二个原因请参见 David Carlisle 的评论)。

相关内容