## Friday, February 27, 2009

### table

One of my last posts was on how to define the width of a column in a table (see here).

The parbox (p), which is used by Latex when you define the column width, will by default align its content on the left. This can be changed, but is a bit tricky.

The keyword is:

1.
\raggedleft,
2.
\centering or
3.
\raggedright

Raggedleft will align text on the right-hand side, leaving whatever white space is remaining (ragged) on the left.
For a better understanding, let’s define right alignment of the text as a new column type “x”, which can than be used in the very same way as pre-defined column types.
Defining a new column type needs the following package:

1.
\usepackage{array}

and than:

1.
\newcolumntype{x}[1]{%
2.
>{\raggedleft\hspace{0pt}}p{#1}%

The argument is the width of the column.

Now simply use “x{2cm}” instead of “p{2cm}”, for columns which align text on the right. By changing \raggedleft to \centering, you can align text in the centre.

Example:

1.
\begin{table}\centering
2.
\begin{tabular}{|l|x{4.5cm}|x{4.5cm}|}\hline
3.
4.
1 & a & b \tabularnewline\hline
5.
2 & b & a \tabularnewline\hline
6.
\end{tabular}
7.
\end{table}

Note:
An important last thing to mention, you cannot end lines with “\\”, as you defined your own column type. Therefore, I am using \tabularnewline in the example. If you want to save time, you might define your own command as follows:

1.
\newcommand{\tn}{\tabularnewline}

Or even:

1.
\newcommand{\tnhl}{\tabularnewline\hline}