类似于 html 的表格环境

类似于 html 的表格环境

我如何模拟 HTML 表格?即:我想给表格一个最大宽度(例如\textwidth),并且表格应根据每个单元格的内容自动分配必要的空间。

因此结构如下:

<table border="1">
  <tr>
    <td>foo</td><td>this is a longer text<br /> with a few lines that might be even without<br/> sense</td>
  </tr>
  <tr>
    <td>bar</td><td>not so long</td>
  </tr>
</table>

应产生类似如下的结果:

在此处输入图片描述

答案1

@StephanLehmke 给了我提示:

\documentclass[paper=a4]{scrartcl}
\usepackage{tabu}

\begin{document}
\begin{tabu}spread 0pt{|X[-1]|X|}
\hline
foo & this is a longer text\par with a few lines that might be even without\par sense \\
bar & not so long \\
\hline
\end{tabu}

\end{document}

这使:

在此处输入图片描述

答案2

tabulary模拟 HTML 是 David Carlisle 的包(因y之后出现而得名)使用的算法x

\documentclass{article}
\usepackage{tabulary}
\begin{document}
\begin{tabulary}{0.4\linewidth}{|LL|}
   foo & this is a longer text\newline
         with a few lines that might be even without\newline
         sense\\
   bar & not so long
\end{tabulary}
\end{document}

垂直线只是为了显示盒子的范围。我应该更经常使用这个包装;它看起来做得很好。

答案3

您也可以通过包获得这一点tabularx,但如果没有包的垂直规则和水平规则看起来会更好booktabs

平均能量损失

\documentclass{scrartcl}
\usepackage{tabularx,booktabs}
\begin{document}
\noindent\begin{tabularx}{.4\linewidth}{lX}
\toprule
foo & this is a longer text\par
with a few lines that might be even without\par
sense \\
\midrule
bar & not so long \\
\bottomrule
\end{tabularx}
\end{document}

相关内容