垂直对齐表格中的单个单元格而不破坏行间距

垂直对齐表格中的单个单元格而不破坏行间距

我一直在试驾大卫卡莱尔的解决方案垂直对齐表格中的单个单元格,但我发现这会破坏与上一行之间的垂直间距(请参阅下面的 MWE)。除了手动估计所需的行间距调整之外,有没有更聪明或更优雅的方法来解决这个问题?

\documentclass[12pt]{article}
\usepackage{tabularx}
\begin{document}
  \begin{table}[h]
    \begin{tabularx}{0.5\linewidth}{X r}
      A row heading & 123 \\
      A second row heading that is very long and will surely break & 456 \\
      A third row heading & 789 \\
    \end{tabularx}
  \end{table}
  \clearpage
  \begin{table}[h]
    \begin{tabularx}{0.5\linewidth}{X r}
      A row heading & 123 \\
      \parbox[b]{\hsize}{A second row heading that is very long and will surely break} & 456 \\
      A third row heading & 789 \\
    \end{tabularx}
  \end{table}
\end{document}

动画 MWE

答案1

如果希望表格的所有行都沿 X 型单元格的底部基线对齐,我建议您运行

 \renewcommand\tabularxcolumn[1]{b{#1}}

装完tabularx包裹后。无需\parbox包装纸。

在此处输入图片描述

\documentclass[12pt]{article}
\usepackage{tabularx}
\renewcommand\tabularxcolumn[1]{b{#1}} % <-- new

\begin{document}
\begin{table}[h]
  \begin{tabularx}{0.5\linewidth}{X r}
    A row heading & 123 \\
    A second row heading that is very long and will surely break & 456 \\
    A third row heading & 789 \\
  \end{tabularx}
\end{table}
\end{document}

答案2

第二个表格的高度\parbox超过了支撑的高度,支撑的高度使得由单行文本组成的单元格的文本基线之间的距离。因此,它\parbox没有对齐,因此其第一行文本的基线与相邻单元格的基线不齐,但它的上边界线与\parbox上方表格单元格的框的下边界线相邻。

只要您不使用\arraystretchand/or ,您就可以在内容前面\extrarowheight添加和附加s以确保适当的高度和深度:\strut\parbox

\documentclass[12pt]{article}
\usepackage{tabularx}
\begin{document}
  \begin{table}[h]
    \begin{tabularx}{0.5\linewidth}{X r}
      A row heading & 123 \\
      A second row heading that is very long and will surely break & 456 \\
      A third row heading & 789 \\
    \end{tabularx}
  \end{table}
  \clearpage
  \begin{table}[h]
    \begin{tabularx}{0.5\linewidth}{X r}
      A row heading & 123 \\
      \parbox[b]{\hsize}{\strut A second row heading that is very long and will surely break\strut} & 456 \\
      A third row heading & 789 \\
    \end{tabularx}
  \end{table}
\end{document}

在此处输入图片描述

更好的方法可能是加载包数组并定义用于底部对齐的列类型 -\TX@col@width是 X 列的宽度:

\documentclass[12pt]{article}
\usepackage{tabularx, array}
\makeatletter
\newcolumntype{B}{b{\TX@col@width}}%
\makeatother
\begin{document}
  \begin{table}[h]
    \begin{tabularx}{0.5\linewidth}{X r}
      A row heading & 123 \\
      A second row heading that is very long and will surely break & 456 \\
      A third row heading & 789 \\
    \end{tabularx}
  \end{table}
  \clearpage
  \begin{table}[h]
    \begin{tabularx}{0.5\linewidth}{B r}
      A row heading & 123 \\
      A second row heading that is very long and will surely break & 456 \\
      A third row heading & 789 \\
    \end{tabularx}
  \end{table}
\end{document}

在此处输入图片描述

相关内容