6

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 Answer 1

7

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}
5
  • 5
    @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, 2017 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, 2017 at 14:58
  • @daleif do you want to post an own answer or should I just edit mine?
    – torkleyy
    Jan 19, 2017 at 7:10
  • I don't hunt posts, so just update yours.
    – daleif
    Jan 19, 2017 at 7:15
  • Leaving it there because I think it might help: it's probably better to put \phantomsection before the unnumbered section, so that when clicking on it, the hyperlink brings you right above the section title, instead of below it (which is a behaviour I found quite irritating ahah) :-)
    – mikyll98
    Jul 11, 2023 at 21:08

You must log in to answer this question.

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