0

I want to add a table caption with a label in a longtable environment. The caption should appear in a multicolumn, colored table cell.

The following doesn't work as expected:

\documentclass[12pt]{article}

\usepackage{longtable}
\usepackage{color}
\usepackage{xcolor}
\usepackage{colortbl}

\begin{document}

\begin{longtable}{|c|c|}
    \hline
    \multicolumn{2}{|c|}{\cellcolor{gray!40}\caption{My Table Caption}\label{table1}} \\
    \hline
    1 & 2\\ \hline
    3 & 4\\ \hline
\end{longtable}

\end{document}

Changing the \caption into, for example, \textbf works.

How can I get the \caption working in a longtable cell?

4
  • Why put the caption in a cell?
    – Bernard
    Nov 2, 2020 at 15:29
  • From the longtable documentation: "The \caption{...} command is essentially equivalent to \multicolumn{n}{c}{\parbox{\LTcapwidth}{...}} wheren is the number of columns of the table".
    – leandriis
    Nov 2, 2020 at 15:29
  • @Bernard: I want to add the caption on top of the table, alignment center with a grey background, full table width and a black border. I am happy if you can show me another possibility than a table cell.
    – mhellmeier
    Nov 2, 2020 at 15:44
  • 1
    I would copy the definition of \LT@makecaption from the package and add the colours etc there (\LT@mcol in that definition is essentially \multicolumn) Nov 2, 2020 at 15:55

1 Answer 1

0

Got it working, thanks to the comments above!

After redefining \LT@makecaption I could solve it by only adding \caption{...}\label{...} \\ to the table.

Here is the working version from the code above:

\documentclass[12pt]{article}

\usepackage{longtable}
\usepackage{color}
\usepackage{xcolor}
\usepackage{colortbl}

% redefine longtable caption
\makeatletter
\def\LT@makecaption#1#2#3{%
    \multicolumn{\LT@cols}{|c|}{\cellcolor{gray!40}\textbf{#2: }\textbf{#3}}
}
\makeatother

\begin{document}

\begin{longtable}{|c|c|}
    \hline
    \caption{My Table Caption}\label{table1}\\
    \hline
    1 & 2\\ \hline
    3 & 4\\ \hline
\end{longtable}

\end{document}

You must log in to answer this question.

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