Set the column width of a table in LaTeX (p, tabularx)
A p{3cm} column is 3 cm wide and wraps its text. To make a table exactly as wide as the text block, use tabularx: its X columns share the width that the other columns leave free.
Preamble
The snippets on this page need these lines before \begin{document}:
\usepackage{array}
\usepackage{tabularx}Give a column a fixed width
p{4cm} takes any length, also a relative one such as p{0.3\textwidth}. The text is justified, and its first line stands level with the other cells of the row.
\begin{tabular}{lp{4cm}}
\hline
Term & Meaning \\
\hline
Float & An environment that LaTeX moves to a place where it fits. \\
Rule & A horizontal line in a table. \\
\hline
\end{tabular}Fill the text width with tabularx
tabularx takes the total width as its first argument. Each X column behaves like a p column whose width LaTeX computes; several X columns get the same width.
\noindent
\begin{tabularx}{\textwidth}{lX}
\hline
Term & Meaning \\
\hline
Float & An environment that LaTeX moves to a place where it fits, for example the top of the next page. \\
Rule & A horizontal line in a table. \\
\hline
\end{tabularx}Center or right-align a fixed-width column
With the array package, >{...} puts commands in front of every cell of a column. \centering, \raggedright or \raggedleft set the alignment, and \arraybackslash makes \\ end the row again. \newcolumntype saves the combination under one letter.
\newcolumntype{C}[1]{>{\centering\arraybackslash}p{#1}}
\newcolumntype{R}[1]{>{\raggedleft\arraybackslash}p{#1}}
\begin{tabular}{|l|C{3cm}|R{2cm}|}
\hline
Item & Origin & Price \\
\hline
Apple & Lake Constance & 0.50 \\
\hline
\end{tabular}Give X columns different widths
>{\hsize=1.5\hsize}X makes a column 1.5 times as wide as a normal X column. The factors of all X columns have to add up to the number of X columns, here 1.5 + 0.5 = 2.
\noindent
\begin{tabularx}{\textwidth}{l>{\hsize=1.5\hsize}X>{\hsize=0.5\hsize}X}
\hline
Term & Meaning & Example \\
\hline
Float & An environment that LaTeX moves to a place where it fits. & \texttt{table} \\
\hline
\end{tabularx}Pitfalls
- The length in
p{...}is the width of the text. LaTeX adds the padding\tabcolsep(6 pt by default) on both sides of every column, so twop{0.5\textwidth}columns are 24 pt wider than the text block. - A narrow justified column gets wide gaps between the words and Underfull \hbox (badness 10000) in paragraph at lines 3--4 warnings.
>{\raggedright\arraybackslash}p{3cm}sets the column ragged right instead.
Compiled with pdfLaTeX from TeX Live 2023.
Related pages
- Package
tabularx - Package
array - How-to Fit a table that is too wide in LaTeX
- How-to Align text in table cells in LaTeX
- Error Underfull \hbox (badness 10000) in paragraph at lines 3--4