请查看以下MEW:
\documentclass[demo]{article}
\usepackage[english]{babel}
\usepackage{graphicx}
\usepackage{xcolor,booktabs,caption}
\begin{document}
\captionsetup[table]{box=colorbox,boxcolor=orange!20}
\captionof{table}{The first table}
\centerline{
\fcolorbox{yellow!20}{yellow!20}{
\begin{tabular}{p{0.4\textwidth}p{0.3\textwidth}}
\toprule
Gender & No.(\%)\\
\midrule
Female & 4 (21.1) \\
Male & 15 (78.9) \\
\midrule
Total & 19 (100.0) \\
\bottomrule
\tiny{Source: Airtel Data}
\end{tabular}
}
}
\end{document}
现在上面的内容产生以下内容:
但我希望标题的宽度与表格的宽度完全匹配。有什么想法吗?[请忽略列标题,与代码不匹配,但在这种情况下应该无关紧要]
答案1
表格可以放入一个框中,框的宽度用于\parbox
(或minipage
),限制标题的宽度:
\documentclass[demo]{article}
\usepackage[english]{babel}
\usepackage{graphicx}
\usepackage{xcolor,booktabs,caption}
\captionsetup[table]{box=colorbox,boxcolor=orange!20}
\newsavebox\measurebox
\begin{document}
\sbox\measurebox{%
\fcolorbox{yellow!20}{yellow!20}{%
\begin{tabular}{p{0.4\textwidth}p{0.3\textwidth}}
\toprule
Gender & No.\@ (\%)\\
\midrule
Female & 4 (21.1) \\
Male & 15 (78.9) \\
\midrule
Total & 19 (100.0) \\
\bottomrule
\tiny{Source: Airtel Data}
\end{tabular}%
}%
}
\begin{center}
\parbox{\wd\measurebox}{%
\centering
\setlength{\abovecaptionskip}{0pt}
\setlength{\belowcaptionskip}{0pt}
\captionof{table}{The first table}
\usebox\measurebox
}%
\end{center}
\end{document}
评论:
该示例还通过注释行尾来删除不需要的空格。这些空格实际上很重要,因为它们是在水平模式下设置的。
\abovecaptionskip
通过将和设置为零,可以删除标题周围的间距\belowcaptionskip
。(由于标题位于表格上方,“上方”和“下方”的逻辑有点令人困惑地颠倒了。\abovecaptionskip
在标题和表格之间使用,也\vspace{-\abovecaptionskip}
可以使用。)
带有一些手动数字对齐的变体:
Female & \leavevmode\phantom{0}4 \phantom{1}(21.1) \\
Male & 15 \phantom{1}(78.9) \\
或者
Gender &
\sbox{\measurebox}{19 (100.0)}%
\leavevmode\rlap{No.}%
\kern\wd\measurebox
\llap{(\%)}\\
\midrule
Female & \leavevmode\phantom{0}4 \phantom{1}(21.1) \\
Male & 15 \phantom{1}(78.9) \\