4

I am trying to make the last column of my table a fixed width, so that the text in the second row will wrap around. I've tried using p{<width>} to define this, but the column stays the same width no matter what value I use:

    \begin{center}
     \begin{tabular}{|l | c | c | c | p{3cm} |} 
        \hline
        & COL1 & COL2 & COL3 \\
        \hline 
        row text aligned to left & row & row & larger text that needs to 
        wrap \\
        \hline
     \end{tabular}
    \end{center}

I've also tried adding \newline inside the cell, with no changes.

CarLaTeX
  • 62,716
  • Welcome to TeX.SX! Your long text is in a c column, not in the last. Just remove one c from your column definition. – TeXnician Jun 19 '17 at 05:50

1 Answers1

6

The number of column definitions should coincide with the number of columns you actually use.

If column definition number is greater than the actual column number, TeX simply ignores the last column definitions.

If column definition number is lower than the actual column number, TeX givers the error: Extra alignment tab has been changed to \cr.

Hence, as TeXnician already told you, you have to leave a c | if you have 4 columns.

To center the p{...} column, just put >{\centering\arraybackslash} before its definition.

For convenience, you can also define a new column type and use it as I've done in the second table in my MWE.

I have also increased a bit the row height redefining \arraystretch.

\documentclass{article}
\usepackage{array}
\newcolumntype{C}{>{\centering\arraybackslash}p{2.5cm}}% for convenience you can also define a new column type

\renewcommand*{\arraystretch}{1.2}%... and increase the row height

\begin{document}
    If you have 4 columns in total:
    \begin{center}
        \begin{tabular}{|l | c | c | >{\centering\arraybackslash}p{2.5cm} |} 
            \hline
            & COL1 & COL2 & COL3 \\
            \hline 
            text aligned to left & centered & centered & larger text that needs to 
            wrap \\
            \hline
        \end{tabular}
    \end{center}

    If you have 5 columns in total:
    \begin{center}
        \begin{tabular}{|l | c | c | c | C |} 
            \hline
            & COL1 & COL2 & COL3 & COL4 \\
            \hline 
            text aligned to left & centered & centered & another cell & larger text that needs to 
            wrap \\
            \hline
        \end{tabular}
    \end{center}
\end{document}

enter image description here

CarLaTeX
  • 62,716