How to add a forced line break inside a table cell
Strangely, no answer (unless I've misread them) mentions a package that is dedicated to this precise question: makecell
, which allows for common formatting of certain cells, thanks to its \thead
and \makecell
commands, and for line breaks inside these cells. The horizontal and vertical alignments can chosen independently from those of the table they're included in. The default is cc
, but you can change it globally in the preamble with
\renewcommand{\cellalign/theadalign}{vh}
where v is one of t,c,b
and h one of l,c,r
. Alternatively, for a single cell, you can use the \makecell
or \thead
commands with the optional argument [vh]
.
So here is a demo:
\documentclass[12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{fourier}
\usepackage{array}
\usepackage{makecell}
\renewcommand\theadalign{bc}
\renewcommand\theadfont{\bfseries}
\renewcommand\theadgape{\Gape[4pt]}
\renewcommand\cellgape{\Gape[4pt]}
\begin{document}
\begin{center}
\begin{tabular}{ | c | c | c |}
\hline
\thead{A Head} & \thead{A Second \\ Head} & \thead{A Third \\ Head} \\
\hline
Some text & \makecell{Some really \\ longer text} & Text text text \\
\hline
\end{tabular}
\end{center}
\end{document}
It's a quite old question, but I'll add my answer anyway, as the method I suggest didn't appear in the others
\begin{tabular}{|c|c|c|}
\hline
Foo bar & \begin{tabular}[x]{@{}c@{}}Foo\\bar\end{tabular} & Foo bar \\
\hline
\end{tabular}
where x
is either t
, c
, or b
to force the desired vertical alignment.
In case this is needed in more than a couple of places, it's better to define a command
\newcommand{\specialcell}[2][c]{%
\begin{tabular}[#1]{@{}c@{}}#2\end{tabular}}
so the table line before can be one of
Foo bar & \specialcell{Foo\\bar} & Foo bar \\ % vertically centered
Foo bar & \specialcell[t]{Foo\\bar} & Foo bar \\ % aligned with top rule
Foo bar & \specialcell[b]{Foo\\bar} & Foo bar \\ % aligned with bottom rule
More variations are possible, for instance specifying also the horizontal alignment in the special cell.
Notice the @{}
to suppress added space before and after the cell text.
It really is no wonder why LaTeX is said to be complicated! Just look at your answers to such an easy question! How about an easy solution to an every day problem?
\usepackage{pbox}
\begin{tabular}{|l|l|} \hline
\pbox{20cm}{This is the first \\ cell} & second \\ \hline
3rd & and the last cell \\ \hline
\end{tabular}
which looks like:
Note that the width supplied to \pbox
is a maximum width. If the content is shorter the length of the longest line is taken.