# how to have a caption on top of longtable?

I want to have a longtable like this:

\begin{center}
\begin{longtable}{|p{2cm}|p{3cm}|p{7cm}|p{3cm}|}
\caption{my caption}
\hline
1 & 2 & 3 & 4\\
\hline
\hline
1 & 2 & 3 & 4\\
\hline
1 & 2 & 3 & 4\\
\hline
.
.
.
1 & 2 & 3 & 4\\
\hline

\label{variability_impl_mech}
\end{longtable}
\end{center}


but when I try to compile this, I get this error: !Misplaced \noalign

when I write the caption after the last \hline, it works fine. I want to have the caption on top of my table but this error appears.

• To start with, remove the \begin{center} and \end{center} instructions -- a longtable is automatically centered. Second, add a double backslash after \caption{...}.
– Mico
Dec 22, 2014 at 20:44

\begin{longtable}{|p{2cm}|p{3cm}|p{7cm}|p{3cm}|}
\caption{my caption}\\    %%%%<===
\hline


and you should put the \label after \caption, which makes more sense.

• As an addition to the original answer using the label after caption should be as \caption{my caption} \label{my label}\\ not as \caption{my caption}\\ \label{my label} Jul 7, 2018 at 20:52
• For me it doesn't compile without \endfirsthead and \endhead. See @Benjamin McKay's answer. Sep 17, 2020 at 6:59
• In my current version of Miktex (and when pushed up to overleaf), compilation would stall and hang without adding the "\\" after the caption command. Hopefully that will help others running into this problem in the current version. Nov 18, 2020 at 15:59

\documentclass{article}
\usepackage{longtable}
\begin{document}

\begin{longtable}{|p{2cm}|p{3cm}|p{7cm}|p{3cm}|}
\caption{my caption}
\label{variability_impl_mech}
\hline
1 & 2 & 3 & 4\\
%\hline
\hline
1 & 2 & 3 & 4\\
\hline
1 & 2 & 3 & 4\\
\hline
.
.
.
1 & 2 & 3 & 4\\
\hline
\end{longtable}

\end{document}

• This is the only way it worked for me, with a \label after \caption. Mar 21, 2021 at 23:03

I had a problem with it, because I generate my tables with the library pandas from python. In this way.

print(tabla_1.to_latex(index = False, longtable=True))


But the problem is that pandas generate my longtables in this way:

\begin{longtable}{lrrr}
\toprule
Nombre &  No datos &  P. rango &  total\_isnull \\
\midrule


So I tried to put \labeland \caption before \toprule, but it nevers compile. So my solution was change \toprule for \hline and then you'll have your compilation, example:

\begin{longtable}{lrrr}
\label{YourLabel}
\Caption{YourCaption}
\hline
Nombre &  No datos &  P. rango &  total\_isnull \\
\midrule

• I create tables using pandas in the same way and I find things work properly when placing \caption{the caption}\label{the label}\\ after the \begin{longtable} line as mentioned by @Herbert Jan 7, 2019 at 17:36
• \toprule requires the booktabs package I believe. Mar 25, 2019 at 19:00