如何强制表格适合页面宽度?

如何强制表格适合页面宽度?

我有下表:

\begin{table}[htb]
\begin{tikzpicture}
\node (table) [inner sep=0pt] {
\begin{tabular}{ l | l }
  {\bf Symptom} & {\bf Metric} \\
\hline
Class that has many accessor methods and accesses a lot of external data & ATFD is more than a few\\
Class that is large and complex & WMC is high\\
Class that has a lot of methods that only operate on a proper subset of the instance variable set & TCC is low\\
\end{tabular}
};
\draw [rounded corners=.5em] (table.north west) rectangle (table.south east);
\end{tikzpicture}
\caption{God class symptoms}
\label{tbl:god_class}
\end{table}

现在我想强制表格的宽度与 相同\textwidth,方法是对表格文本进行换行或缩放。我该如何实现?

答案1

您可以使用tabularx包。它允许您设置表格的宽度并提供X列类型,以填充剩余的空间。它可以用于多列,然后平等地共享剩余的宽度。

例子:

\usepackage{tabularx} % in the preamble
% ....
\begin{tabularx}{\textwidth}{X|l}
  \textbf{Symptom} & \textbf{Metric} \\
\hline
Class that has many accessor methods and accesses a lot of external data & ATFD is more than a few\\
Class that is large and complex & WMC is high\\
Class that has a lot of methods that only operate on a proper subset of the instance variable set & TCC is low\\
\end{tabularx}

通常,也可以使用p{<width>}而不是l作为列类型来设置列的宽度。然后它将被格式化为段落,并且可以包含换行符。<width>用所需的宽度替换。

答案2

再提一下另一种方法:tabular*环境。假设您有一个包含 6 个居中对齐列的表格。您可以通过如下设置强制它占据文本块的整个宽度:

\setlength\tabcolsep{0pt}
\begin{tabular*}{\linewidth}{@{\extracolsep{\fill}} cccccc }
...
\end{tabular*}

与通过扩展部分或全部表格列的宽度来工作的tabularx和环境不同,tabularytabular*,环境通过扩展列间空白。顺便说一句,当使用扩展设备tabular*的环境时@{\extracolsep{\fill}},不应在表中使用垂直规则。

从技术上来说,该指令\setlength\tabcolsep{0pt}是可选的。但是,如果表格材料超出\linewidth默认值\tabcolsep(通常但不总是 6pt),则该指令通常非常有用。

就我个人而言,我怀疑需要记住插入@{\extracolsep{\fill}}才使得这种方法的流行度有所降低......

答案3

这是一个简单的方法:

\newlength\q
\setlength\q{\dimexpr .5\textwidth -2\tabcolsep}
\noindent\begin{tabular}{p{\q}p{\q}}
alfa & bravo \\
charlie & delta
\end{tabular}

答案4

您还可以使用graphicx包 - 我从以下在线表生成器中找到了此解决方案:http://www.tablesgenerator.com/

您只需要添加一个重新调整表格大小的“resizebox”命令,如下所示:

% Please add the following required packages to your document preamble:
% \usepackage{graphicx}

\begin{table}[htb]
\resizebox{\textwidth}{!}{% use resizebox with textwidth
\begin{tabular}{ l | l }
  {\bf Symptom} & {\bf Metric} \\
\hline
Class that has many accessor methods and accesses a lot of external data & ATFD is more than a few\\
Class that is large and complex & WMC is high\\
Class that has a lot of methods that only operate on a proper subset of the instance variable set & TCC is low\\
\end{tabular}% close resizebox
}
\end{table}

注意:这将缩放整个表格,包括字体。

相关内容