How to create a table with fixed column widths

The standard column types are l, c, r and p which stands for left aligned, centered or right alignment and parbox.

Only the p - type can have a width argument, i.e. p{somewidth}, where width can be specified with any dimension TeX/LaTeX knows of.

The p - type is effectively \parbox which allows wrapping of text and content, which isn't possible (directly) in a l etc. type, for example an itemize or enumerate list.

The array package provides for example for the m type which is meant for vertical ('middle') aligned. In addition to this, array has the \newcolumntype macro which allows to define other column types, however, based on the existing 'base' types, i.e. r, l, c or p.

The tabularx package provides for the X columntype and the siunitx enables to use the S columntype.

Here's a small sample code for showing the width effects:

\begin{tabular}{|p{4cm}|p{6cm}|} will provide a tabular, that has the width of 4cm + 5cm + 4\tabcolsep + 3\arrayrulewidth, since each column has a left and right \tabcolsep space, the later defaulting to 6pt; and there are three |, so 3\arrayrulewidth lengths are added.

In total, even p{4cm}p{5cm} will be wider than the expected 9cm.

\documentclass{article}



\begin{document}

\begin{tabular}{|p{4cm}|p{5cm}|}
\hline
foo & bar
\end{tabular}

\begin{tabular}{|@{}p{4cm}@{}|@{}p{5cm}@{}|}
\hline
foo & bar
\end{tabular}


{%
 \renewcommand{\arrayrulewidth}{0pt}%
 \begin{tabular}{@{}p{4cm}@{}@{}p{5cm}@{}}
   foo & bar
 \end{tabular}
}

\end{document}

This workaround in the preamble solves the problem. You can simply use C{width} for centered entries. Replace C with L or R if raggedright or raggedleft is favoured.

\usepackage{array}
\newcommand{\PreserveBackslash}[1]{\let\temp=\\#1\let\\=\temp}
\newcolumntype{C}[1]{>{\PreserveBackslash\centering}p{#1}}
\newcolumntype{R}[1]{>{\PreserveBackslash\raggedleft}p{#1}}
\newcolumntype{L}[1]{>{\PreserveBackslash\raggedright}p{#1}}

Tags:

Tables