[Tex/LaTex] How to center table caption that includes a newline

captionsline-breakingtables

My table caption spans more than on line so I added a \newline to split the caption at an appropriate position. Now, the two lines are left aligned. How do I center the two lines of the caption?

\begin{table}[htb]
\begin{center}
\caption{my caption line one\newline my caption line two}
\begin{tabular}{|r|c|c|c|c|c|}
\end{tabular}
\end{center}
\end{table}

Best Answer

Package caption allows many customizations. Centered caption texts can be achieved by option justification=centering.

  However, because of the manual line break, the result isn't too pleasing. Therefore I have added an own format using centering inside environment varwidth of package varwidth. It cuts down the lines to the needed length.

  The third table adds labelsep=newline to add a first line for the table label.

\documentclass{article}
\usepackage{caption}

\usepackage{varwidth}
\DeclareCaptionFormat{myformat}{%
  % #1: label (e.g. "Table 1")
  % #2: separator (e.g. ": ")
  % #3: caption text
  \begin{varwidth}{\linewidth}%
    \centering
    #1#2#3%
  \end{varwidth}%
}
% \captionsetup{format=myformat}% global activation

\begin{document}

  \begin{table}[htb]
    \centering
    \captionsetup{justification=centering}
    \caption{my caption line one\newline my caption line two}
    \begin{tabular}{|r|c|c|c|c|c|}
      \hline
      \verb|\captionsetup{justification=centering}|\\
      \hline
    \end{tabular}
  \end{table}

  \captionsetup{format=myformat}

  \begin{table}[htb]
    \centering
    \caption{my caption line one\newline my caption line two}
    \begin{tabular}{|r|c|c|c|c|c|}
      \hline
      \verb|\captionsetup{format=myformat}|\\
      \hline
    \end{tabular}
  \end{table}

  \captionsetup{labelsep=newline}

  \begin{table}[htb]
    \centering
    \caption{my caption line one\newline my caption line two}
    \begin{tabular}{|r|c|c|c|c|c|}
      \hline
      \verb|\captionsetup{format=myformat, labelsep=newline}|\\
      \hline
    \end{tabular}
  \end{table}
\end{document}

Result

Tested with the following versions (\listfiles):

 *File List*
 article.cls    2007/10/19 v1.4h Standard LaTeX document class
  size10.clo    2007/10/19 v1.4h Standard LaTeX file (size option)
 caption.sty    2013/05/02 v3.3-89 Customizing captions (AR)
caption3.sty    2013/05/02 v1.6-88 caption3 kernel (AR)
  keyval.sty    1999/03/16 v1.13 key=value parser (DPC)
varwidth.sty    2009/03/30 ver 0.92;  Variable-width minipages
 ***********