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.

1
  • 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, 2017 at 5:50

1 Answer 1

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

2
  • thank you. Is there a way to use a p-column and still have the rows centered? Jun 19, 2017 at 6:17
  • @PatzKareshet See my renewed answer. Thank you for accepting it, and don't hesitate to post other questions if you need help!
    – CarLaTeX
    Jun 19, 2017 at 6:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .