如何设置精确的 ``表格'' 宽度

如何设置精确的 ``表格'' 宽度

我使用tabular环境并指定每列的宽度,如下所示。但我想知道为什么列数越多,表格越宽,尽管列宽总和始终是一条完整的线宽。

有没有什么方法可以确保指定的所有列宽都具有精确的表格宽度?

在此处输入图片描述

\documentclass{article}
\begin{document}

1-column table
\begin{tabular}{ | p{1\linewidth} |}
\hline
    Day\\
\hline
\end{tabular}

\vspace{1cm}

2-column table
\begin{tabular}{|p{0.5\linewidth}|p{0.5\linewidth}|}
\hline
    Day & Day\\
\hline
\end{tabular}

\vspace{1cm}

4-column table
\begin{tabular}{|p{0.25\linewidth}|p{0.25\linewidth}|p{0.25\linewidth}|p{0.25\linewidth}|}
    \hline
    Day & Day & Day & Day\\
    \hline
\end{tabular}

\vspace{1cm}

Why is the table width lengthened as the number of columns increases even though the sum of column widths is one full linewidth alike?

\end{document}

答案1

需要区分的是可用宽度总宽度类型的列p。如果写

\begin{tabular}{ | p{1\linewidth} | }

那么唯一一列的可用宽度确实是1\linewidth。但是,由于列两侧有空白填充,因此仅列的总宽度(不包括两侧的垂直条)就是1\linewidth+2\tabcolsep。整个tabular环境的总宽度将为1\linewidth+2\tabcolsep+2\arrayrulewidth

同样地,对于

\begin{tabular}{|p{0.5\linewidth}|p{0.5\linewidth}|}

两列的可用宽度合计为1\linewidth,两列的总宽度合计为1\linewidth+4\tabcolsep,整个tabular环境的总宽度等于1\linewidth+4\tabcolsep+3\arrayrulewidth

认为可以手动适当调整可用宽度,这样tabular环境的总宽度就恰好为。但是,如果可以使用环境及其列类型1\linewidth,为什么要为这些繁琐的事情烦恼呢?无论出于何种目的,列都是LaTeX 执行所需计算以将整体宽度保持在目标值(通常但不一定为)的列。tabularxXXp1\linewidth

例如,你宁愿写

\begin{tabular}{| *{2}{p{\dimexpr0.5\linewidth-2\tabcolsep-1.5\arrayrulewidth\relax}|}}

或者

\begin{tabularx}{\textwidth}{|*{2}{X|}}

我相信这个决定绝非难事。


在此处输入图片描述

\documentclass{article}
\usepackage{tabularx}
\begin{document}
\setlength\parindent{0pt} % just for this example

\subsubsection*{Incorrectly constructed 1-, 2-, and 4-column tabular environments}

\begin{tabular}{ | p{1\linewidth} |}
\hline Day \\ \hline
\end{tabular}

\smallskip

\begin{tabular}{|*{2}{p{0.5\linewidth}|}}
\hline Day & Day \\ \hline
\end{tabular}

\smallskip

\begin{tabular}{|*{4}{p{0.25\linewidth}|}}
\hline Day & Day & Day & Day \\ \hline
\end{tabular}


\subsubsection*{Correctly constructed 1-, 2-, and 4-column tabular environments}

\begin{tabular}{|p{\dimexpr1\linewidth-2\tabcolsep-2\arrayrulewidth\relax}|}
\hline Day \\ \hline
\end{tabular}

\smallskip

\begin{tabular}{|*{2}{p{\dimexpr0.5\linewidth-2\tabcolsep-1.5\arrayrulewidth\relax}|}}
\hline Day & Day \\ \hline
\end{tabular}

\smallskip

\begin{tabular}{|*{4}{p{\dimexpr0.25\linewidth-2\tabcolsep-1.25\arrayrulewidth\relax}|}}
\hline Day & Day & Day & Day \\ \hline
\end{tabular}


\subsubsection*{1-, 2-, and 4-column tabularx environments}

\begin{tabularx}{\textwidth}{ | X |}
\hline Day \\ \hline
\end{tabularx}

\smallskip

\begin{tabularx}{\textwidth}{|*{2}{X|}}
\hline Day & Day \\ \hline
\end{tabularx}

\smallskip

\begin{tabularx}{\textwidth}{|*{4}{X|}}
\hline Day & Day & Day & Day \\ \hline
\end{tabularx}

\end{document}

相关内容