Friday, January 22, 2010

Wrapping column text in a table in LaTeX

Let's say you have the following table in LaTeX:

\begin{tabular}{|l|l|}
  \hline
  This is a very very long cell name.  Very long indeed 
  & This is a very, very, very long line that keeps on going even outside of the page!!!!! \\
  \hline
\end{tabular}

The output generated from the above tabular environment is as follows:



As you can see from the above output, the text does not wrap but just keeps going off out of the page.

Introducing the TabularX package


To fix this problem, we will use the tabularx package and use the tabularx environment:

\usepackage{tabularx}

\begin{tabularx}{\linewidth}{|X|X|}
  \hline
  This is a very very long cell name.  Very long indeed 
  & This is a very, very, very long line that keeps on going even outside of the page!!!!! \\
  \hline
\end{tabularx}

The generic template of the tabularx environment is as follows:

\begin{tabularx}{w}{\X\X . . .\}

where:
  • w : the desired width of the table
  • X : marks each column for which the width is to be adjusted

This is now the output with the tabularx environment: