texblog

Cont: Equal cell width (right and centre aligned content)

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:

\raggedleft, \centering or \raggedright

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

\usepackage{array}

\newcolumntype{x}[1]{%
>{\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:

\begin{table}\centering
\begin{tabular}{|l|x{4.5cm}|x{4.5cm}|}\hline
Nb. & Advantage & Disadvantage\tabularnewline\hline
1 & a & b \tabularnewline\hline
2 & b & a \tabularnewline\hline
\end{tabular}
\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:

\newcommand{\tn}{\tabularnewline}

Or even:

\newcommand{\tnhl}{\tabularnewline\hline}

Exit mobile version