[Tex/LaTex] autoref uses wrong name for section, if label occurs after figure

cross-referencinghyperref

I have a document where labels occur inside of sections, i.e., not only at the beginning of a section. If the section contains environments, then autoref wronlgy uses for all following labels the name of this environment, but still uses the correct numbering of the section. Moving the label definitions to the top of the section is not an option in my setup. Here is a minimal example:

\documentclass{article}
\usepackage{hyperref}

\begin{document}
\section{ABC}
\section{DEF}
\label{sec:DEFup}

Correctly is section 2: \autoref{sec:DEFup}

\begin{figure}
  \centering
  XXX
  \caption{Three X's}
\end{figure}

\label{sec:DEFdown}
\noindent
Should be section 2, but is Figure 2, which does not even exist:
\autoref{sec:DEFdown}

\end{document}

Best Answer

The behavior you describe as erroneous is, in fact, entirely correct according to the hyperref syntax rules: the argument of a \label command is "attached" to the most recently encountered entity that can receive a label.

In your example, the second \label command is encountered after a figure environment is set up and is given a caption. Thus, the hyperref package (which provides the autoref command) must assign the label sec:DEFdown to the figure environment. The fact that the label string in the example contains the substring "sec:" does not affect the element to which it will be assigned.

The uptake:

  • Always aim to issue \label directives immediately following the associated sectioning or captioning command. Keep in mind that environments such as equations can also be assigned \labels for cross-referencing purposes.
  • In the case of floats such as figures and tables, be sure to provide the \label command before the float environment ends -- but also, of course, after the float's \caption command is issued.
Related Question