2

I'm trying to create links from my table of contents to the corresponding sections using hyperref.

However, I've noticed that if the first entry is an unnumbered section (\section*), the link just brings me to the table of contents.

Here's a small example to illustrate what I'm trying to say. Note that the second unnumbered section works while the first does not. Also, using a numbered section as the first entry would fix the problem.

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage{hyperref}
\hypersetup{
    colorlinks=true,
    linktoc=all,
    linkcolor=black,
}

\begin{document}

\tableofcontents

\newpage

\addcontentsline{toc}{section}{Unnumbered section 1}
\section*{Unnumbered section 1}

\addcontentsline{toc}{section}{Unnumbered section 2}
\section*{Unnumbered section 2}

\end{document}

How can I have the first link so that it targets the correct page?

1

I found out that using \addcontentsline just after \section* fixes the problem.

So the corrected code would be

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage{hyperref}
\hypersetup{
    colorlinks=true,
    linktoc=all,
    linkcolor=black,
}

\begin{document}

\tableofcontents

\newpage

\section*{Unnumbered section 1}
\addcontentsline{toc}{section}{Unnumbered section 1}

\section*{Unnumbered section 2}
\addcontentsline{toc}{section}{Unnumbered section 2}

\end{document}

As pointed out by @daleif, you should add \phantomsection before \addcontentsline if you use hyperref.

So just like

\phantomsection
\addcontentsline{toc}{section}{Name}
\section{Name}
  • 3
    @toekleyy remember \phantomsection right before \addcontentsline, the hyperlink needs something to grap hold of, normally it would here use the section counter, but it is not in use, so we need \phantomsection to help it. – daleif Jan 18 '17 at 14:16
  • @daleif ah I see. Adding \phantomsection fixed it, too. I wonder why it worked by just flipping the commands – torkleyy Jan 18 '17 at 14:58
  • @daleif do you want to post an own answer or should I just edit mine? – torkleyy Jan 19 '17 at 7:10
  • I don't hunt posts, so just update yours. – daleif Jan 19 '17 at 7:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.