Skip to content
ImagineWorld

Using Cross-References

node_idnode-book_latex-beginner-s-guide_chapter-07-using-cross-references
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleUsing Cross-References
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In the previous chapters, we created figures and tables and added captions to them. LaTeX automatically takes care of numbering. Documents can also include many other numbered elements, such as pages, sections, and list items. And there’s more: if you’re writing mathematical content, you may want to number equations, theorems, definitions, and other elements as well.

Numbering isn’t just for counting; it also allows us to refer to these elements elsewhere in the document. For instance, in this chapter, if I wanted to direct you to the third figure, I would write “See Figure 7.3.” If you insert another figure, LaTeX will update the numbering of all subsequent figures. But what about the references? LaTeX handles all our cross-references and will update them. So, we should not write a plain reference manually like 7.3, but instead assign internal labels that we can cross-reference later.

In this chapter, we’ll cover the following:

  • Setting labels and references
  • Using advanced referencing
  • Referring to labels in other documents
  • Checking labels and references
  • Turning references into clickable hyperlinks

We’ll work through this using hands-on examples.

To reference a specific part of your document, you first need to mark it using a label. The name you assign to this label is what you’ll use later to reference it.

Let’s walk through a practical example. We’ll typeset a list of the most commonly used LaTeX packages, based on a survey made on https://latex.org. Using the \label command, we’ll mark positions we want to refer to later using the \ref command. Here’s how:

  1. Begin a new book document:
    \documentclass{book}
    \begin{document}
  2. Start a chapter and a section, and add a label to this section:
    \chapter{Statistics}
    \section{Most used packages by LaTeX.org users}
    \label{sec:packages}
  3. Add some body text and a footnote:
    The Top Five packages, used by LaTeX.org
    members\footnote{according to the 2021 survey on
    LaTeX.org\label{fn:project}}:
  4. Write an enumerated list and put a label on a few items:
    \begin{enumerate}
    \item graphicx\label{item:graphicx}
    \item babel
    \item amsmath\label{item:amsmath}
    \item geometry
    \item hyperref
    \end{enumerate}
  5. Add another chapter with a label:
    \chapter{Mathematics}
    \label{maths}
  6. Finish with some text, and refer back to earlier items using the \ref and \pageref commands:
    \emph{amsmath}, on position \ref{item:amsmath}
    of the top list in section~\ref{sec:packages} on
    page~\pageref{sec:packages}, is indispensable to
    high-quality mathematical typesetting in \LaTeX.
    \emph{graphicx}, on position \ref{item:graphicx},
    is for including images. See also the footnote
    \ref{fn:project} on page~\pageref{fn:project}.
    \end{document}
  7. Compile the document and examine the output. Page 1 starts with headings and a bullet list.

Figure 7.1 – First chapter

Figure 7.1 – First chapter

Page 1 ends with a footnote:

Figure 7.2 – Footnote

Figure 7.2 – Footnote

Page 2 is empty since Chapter 2 starts on a right-hand page, which is page 3:

Figure 7.3 – Unresolved references

Figure 7.3 – Unresolved references

  1. Do you see the question marks? Here, references are still missing. Compile again and compare:

Figure 7.4 – Resolved references

Figure 7.4 – Resolved references

We created cross-references using these three commands:

  • \label marks the position
  • \ref prints the number of the element associated with a label
  • \pageref prints the page number where that label occurs

Each of these commands takes the label name as an argument. We can define the names freely.

We had to compile twice because LaTeX requires one run to generate the references that it can read during the next compilation run. If LaTeX can’t resolve a reference yet, you’ll see two question marks in the output.

Let’s now have a closer look at how to create anchor labels and refer to them effectively.

The \label{name} command assigns the current position in the document to the label name. Precisely, it does the following:

  • If you use the \label command in regular text, the label refers to the current sectional unit, such as the chapter or section
  • If the \label command is used inside a numbered environment, such as a figure, table, or numbered list, the label will refer to that environment or item

So, we cannot label a section within a table environment. To avoid any problems because of possible unsuitable positioning, a good rule of thumb is to place the \label command right after the position that we would like to refer to. For instance, place it directly after the corresponding \chapter or \section command.

In the figure or table environments, the \caption command is implicitly responsible for the numbering. That’s why \label has to be placed after \caption, not before.

Floating environments may look like the following:

\begin{figure}[htbp!]
\centering
\includegraphics{filename}
\caption{Test figure}\label{fig:name}
\end{figure}

Here’s how a table with a label may look:

\begin{table}[htbp!]
\centering
\caption{table descripion}\label{tab:name}
\begin{tabular}{cc}
…
\end{tabular}
\end{table}

Label names may include letters, numbers, and punctuation marks, and they are case-sensitive.

In larger documents, the number of labels could be very high, and label management becomes essential. To avoid naming conflicts, it’s a good idea to prefix labels based on the type of environment they represent. It has become common practice to label equations with eq:name, figures with fig:name, tables with tab:name, and sections with sec:name, with similar approaches in other cases. Keep in mind that labels such as fig:1 defeat the purpose, as the idea is to avoid manually setting numbers entirely.

In the following sections, we’ll look at several ways to reference labels.

After assigning a label with a name, we can refer to that name. For this, we use the \ref{name} command. This command prints the number associated with that label, name, which can be, for example, the number of an environment, a list item, or a sectioning element. We can even use \ref{name} before the corresponding \label{name} command appears in the code.

Although the mechanism is simple, it’s quite powerful. Each time we compile a document, LaTeX checks the labels and reassigns the numbers, reflecting all changes in numbering. If LaTeX detects modified labels, it will print a message that another compiler run is required to update the corresponding labels. When in doubt, compile twice.

The \pageref{name} command works similarly to \ref, but instead of returning a number for an element, such as an environment or a section, it prints the page number where the label has been set.

Would all the references still be accurate if we changed the section and page numbers? Let’s try that. Insert a dummy section and a page break at the beginning of our chapter, highlighted here:

\chapter{Statistics}
\section{Introduction}
\newpage
\section{Most used packages by LaTeX.org users}
\label{sec:packages}

Click on Typeset once. LaTeX will compile it, but it will show a message:

LaTeX Warning: Label(s) may have changed. Rerun to get cross-references right.

That’s what we shall do! Click on Typeset a second time, and now all the numbers have been correctly adjusted to section 1.2 and page 2:

Figure 7.5 – Automatically adjusted references

Figure 7.5 – Automatically adjusted references

You can combine both commands. If you’d like to refer to both the section and page number in one sentence, you can write the following:

See figure~\ref{fig:name} on page~\pageref{fig:name}.

As you know how to define a command, you could make such referencing easier:

\newcommand{\fullref}[1]{\ref{#1} on page~\pageref{#1}}
…
See figure~\fullref{fig:name}.

This gives you a comprehensive reference, such as See Figure 4.2 on page 32. However, if the reference, such as for a figure, appears on the same page, writing out the page number looks a bit odd. How can we avoid that? The varioref package offers an elegant solution. We will focus on such advanced referencing in the following sections.

LaTeX helps with automating all kinds of references. It’s not limited to numbering. LaTeX can even generate names and phrases. We will dig deeper into that here.

The varioref package offers commands to add on the preceding page, on the following page, or the page number to a reference, depending on the context.

We will use the two varioref commands to introduce variable references, \vref, and \vpageref, to achieve enhanced reference texts, as follows:

  1. Open our current example from the first section. Add the varioref package to the preamble. Use the nospace package option, which ensures that varioref doesn’t insert additional undesirable space before or after a reference:
    \usepackage[nospace]{varioref}
  2. Modify the content of the second chapter in our example code:
    \emph{amsmath}, on position \vref{item:amsmath}
    of the top list in section~\vref{sec:packages},
    is indispensable to high-quality mathematical
    typesetting in \LaTeX. \emph{graphicx}, on position
    \vref{item:graphicx}, is for including images.
    See also the footnote \vref{fn:project}, that is,
    \vpageref{fn:project}.
  3. Compile twice, and look at the result:

Figure 7.6 – An image at the bottom of the page

Figure 7.6 – An image at the bottom of the page

The \vref command checked the distance from the label of the referenced section. As the label is on the facing page (here, on the preceding page in a two-sided layout), \vref wrote 1.2 on the preceding page.

\vpageref refers to the facing page at the end of the paragraph.

\vref{name} works as follows:

  • If the reference and \label{name} are on the same page, it behaves exactly like \ref and omits the page number.
  • If the reference and the corresponding \label are on adjacent pages, \vref prints the referred number and, additionally, on the preceding page, on the following page, or on the facing page. It will choose the latter if the document is two-sided, that is, if \label and the reference fall onto a double-page spread.
  • If they are farther apart, it will print both \ref and \pageref.

\vpageref is similar to \pageref but behaves like \vref concerning the page reference.

varioref switches between phrasings to have a bit of variation. It can say following page or next page, preceding page or previous page, this page or current page. And in a double-page layout, it switches between facing page and preceding page or next page. With such variation, the text reads more naturally. You can see this alternating phrasing in Figure 7.6.

Even when using varioref, you may still use the standard \ref and \pageref commands alongside the new commands.

When a label and its reference are located close to each other, they may fall on the same page, but not always. In such cases, we usually know whether the label appears above or below the reference. The varioref package allows indicating this using an optional argument to the \vpageref command, as shown below:

see the figure \vpageref[above]{fig:name}

This will print the following:

  • see the figure above, if the figure is on the same page
  • see the figure on the page before, if the figure is on the preceding page

Whereas with the following code, we will have a different output:

see the footnote \vpageref[below]{fn:name}

This will instead print the following:

  • see the footnote below, if the footnote is on the same page
  • see the footnote on the following page, if the footnote is on the next page

The \vpageref command understands two optional arguments. While in the first optional argument, we can state a phrase if the label and reference fall on the same page, in the second optional argument, we can give a phrase for the case when the label and reference fall on different pages. So, we could even write the following:

see the \vpageref[above figure][figure]{fig:name}

This would print the following:

  • see the above figure, if the figure is on the same page
  • see the figure on the previous page, if the figure is on the preceding page

All of this may seem a bit elaborate, but your demands might increase over time, requiring more sophisticated referencing so that these features might come in handy someday.

varioref offers two more commands:

  • \vpagerefrange[opt]{label1}{label2}, where label1 and label2 denote a range (such as a sequence of figures from fig:a to fig:c). If both labels fall on the same page, the result is the same as with \vpageref. Otherwise, the output will be a range, such as on pages 32-36. opt would be used if both labels fall on the current page.
  • \vrefrange[opt]{label1}{label2} is analogous to \vref: see figures \vrefrange{fig:a}{fig:c} may result in see figures 4.2 to 4.4 on pages 36-37.

Visit https://latexguide.org/chapter-07 to see examples.

You can find more information regarding customization in the package manual. As usual, you can open it at the command prompt by typing texdoc varioref or by visiting https://texdoc.org/pkg/varioref.

Tired of repeatedly writing figure~\ref{fig:name} and table~\ref{tab:name}? Wouldn’t it be great if LaTeX could automatically determine the element type meant by \ref{name} and automatically insert the correct reference text with the element name and number for you? What if we want to abbreviate, say, fig.~\ref{fig:name} in the whole document? The cleverev package makes this easy. It automatically detects the type of cross-reference and the context in which it is used.

You can use \cref or \Cref instead of \ref; choose the latter if you wish to capitalize. The corresponding range commands are \crefrange and \Crefrange.

Let’s rewrite our first example to refer using cleveref. To verify that the package acts well, we intentionally omit prefixes in the label names for \label and \cref, as shown here:

  1. Modify our first example of this chapter in the following way. The changed lines are highlighted:
    \documentclass{book}
    \usepackage{cleveref}
    \crefname{enumi}{position}{positions}
    \begin{document}
    \chapter{Statistics}
    \label{stats}
    \section{Most used packages by LaTeX.org users}
    \label{packages}
    The Top Five packages, used by LaTeX.org
    members\footnote{according to the 2021 survey on
    LaTeX.org\label{project}}:
    \begin{enumerate}
    \item graphicx\label{graphicx}
    \item babel
    \item amsmath\label{amsmath}
    \item geometry
    \item hyperref
    \end{enumerate}
    \chapter{Mathematics}
    \label{maths}
    \emph{amsmath}, on \cref{amsmath} of the top list in
    \cref{packages} of \cref{stats}, is indispensable to
    high-quality mathematical typesetting in \LaTeX.
    \emph{graphicx}, on \cref{graphicx}, is for
    including images.
    See also the \cref{project} on \cpageref{project}.
    \end{document}
  2. Click on Typeset twice, and check that references have the correct names:

Figure 7.7 – Automated references

Figure 7.7 – Automated references

As we can see, we don’t need to specify which object we refer to. \cref always chooses the right name and the correct number for us. That’s really useful.

We used the \crefname command to tell cleveref which name it should use for enumerated items. The definition of \crefname is as follows:

\crefname{type}{singular}{plural}

type may be one of chapter, section, figure, table, enumi, equation, theorem, or many other types we have not encountered yet. cleveref uses the singular form for individual references and the plural version for multiple ones. If you need capitalized versions, use \Crefname. So, a typical use may be the following:

\crefname{figure}{fig.}{figs.}
\Crefname{figure}{Fig.}{Figs.}

Also, here, we can refer to ranges using these commands:

  • \crefrange{label1}{label2} to refer to a range of references
  • \cpagerefrange{label1}{label2} to refer to a page range

It will get clearer with an example. Let’s add this line to our current example:

See \crefrange{graphicx}{amsmath} and \cpagerefrange{stats}{maths}.

This gives us: See positions 1 to 3 and pages 1 to 3.

We can sum up the benefits as follows:

  • It reduces the amount of typing.
  • We could use arbitrary label names. The fancyref package does a similar job but relies on prefixes such as chap, fig, or tab.
  • If we decide to change the reference wording, we only need to do it once in the preamble, and it will apply consistently throughout the entire document.

That said, it’s still a good idea to use a prefix such as fig: or sec: to indicate the kind of referenced element. This way, your code would become more understandable – that’s why it’s considered best practice.

Combining smart references with automatic naming

Section titled “Combining smart references with automatic naming”

As the cleveref package is fully compatible with varioref, you can use both to take full advantage of their features. cleveref redefines the varioref commands to internally use \cref. So, you can use the advanced page referencing features of varioref together with the clever naming automation.

Just load varioref before cleveref, as shown here:

\usepackage{varioref}
\usepackage{cleveref}

Now, you may use \vref, \cref, \ref, or the other commands – whichever suits your needs best.

So far, our references have shown only numbers. If you’d like to display the names instead, you can use the nameref package. Start by loading it:

\usepackage{nameref}

Then, use the \nameref command in place of \ref or \pageref, or alongside these commands. In the first example of this chapter, you can write this:

See section~\ref{sec:packages}, \nameref{sec:packages},
on page~\pageref{sec:packages}.

This gives you: See section 1.1, Most used packages by LaTeX.org users, on page 1.

The \nameref command works with regular sectioning commands, including \part and \chapter, as well as with figure and table captions, description list items, and theorem names.

We can also use references to pages, sections, and more across different documents. Let’s take a closer look at this in the next section.

When working on multiple related documents that refer to each other, you might want to use references to labels of another document. The package named xr (short for external references) implements this. First, load the xr package:

\usepackage{xr}

If you need to refer to sections or environments in an external document, say, doc.tex, insert this command into your preamble:

\externaldocument{doc}

This enables you to additionally refer to anything that has been given a label in doc.tex. You may do this for several documents. If you need to avoid conflicts when an external document uses the same \label as the main document, declare a prefix using the optional argument of \externaldocument, which you can use to add a prefix. For example, we can use D- as a prefix:

\externaldocument[D-]{doc}

This way, all references from doc.tex would be prefixed by D-, and you could write \ref{D-name} to refer to name in doc.tex. Instead of D-, you may choose any prefix that makes your labels unique.

Over time, your document may grow, making it hard to remember all label names and where you referred to them. Fortunately, some tools make it easy to inspect and track them.

The showlabels package displays the labels you defined in your PDF output so that you can see them alongside your text. Just load it:

\usepackage{showlabels}

When you compile the same document that we used for Figure 7.1, you’ll see the label names for sections, items, and footnotes right in the output:

Figure 7.8 – Displayed labels

Figure 7.8 – Displayed labels

This can be very useful while writing a longer document. Just be sure you remove it or comment it out before you compile and deliver your final version.

You can customize the appearance of the labels, like this, for example, to see them in bold red:

\renewcommand{\showlabelfont}{\small\bfseries\color{red}}

Another option is to use the showkeys package:

\usepackage{showkeys}

It also shows the labels in the margin, where you defined them, but additionally, it displays the names where you reference them, like this:

Figure 7.9 – Displayed cross-references

Figure 7.9 – Displayed cross-references

This can also help you develop your document.

Labels are meant to be unique identifiers so that LaTeX can reliably decide which object a \ref or \pageref should point to. If you use the same label name more than once, LaTeX issues a warning such as Label name multiply defined. The consequence of such duplicate labels is that cross-references may silently point to the wrong section, figure, table, or equation. LaTeX does not stop compiling, but the resulting output can be inconsistent or misleading.

The warning is written to the .log file, and any serious LaTeX editor will surface duplicate labels as warnings, making them easy to spot and fix.

Prefixing labels with type (sec:, fig:, tab:, eq:), as mentioned earlier in this chapter, dramatically reduces collisions in larger documents.

To check whether all labels and references in your document are actually used, you can load the refcheck package. It helps you identify unused labels, unreferenced equations, and missing references. Let’s say you added \label{item:hyperref}, but you never referred to it.

Simply load the package:

\usepackage{refcheck}

You will see the names of the used labels, and any unused labels will appear with question marks, making them easy to spot:

Figure 7.10 – Highlighting labels without reference

Figure 7.10 – Highlighting labels without reference

In the next section, we’ll see how to make references clickable so readers can jump directly to the referenced element.

PDF can include clickable links and bookmarks. How about exploring that? There’s an outstanding package that offers hyperlink support – the hyperref package.

Try it by loading hyperref right before cleveref. This order is essential for the references to work because cleveref detects whether hyperref has been loaded and makes the references to hyperlinks. Even without any options or commands, your document will be hyperlinked as much as possible because of the following:

  • All references become hyperlinks. Click on any of those numbers to jump to the referred table, list item, section, or page.
  • Each footnote marker is a hyperlink to the footnote text. Click it to jump there.
  • If you insert \tableofcontents, you will get a bookmark list for the documents, chapters, and sections listed in a navigation bar of your PDF reader.

hyperref can do even more for you – linking index entries to text passages, back-referencing of bibliography entries, and more. You can finely customize the behavior using options such as, for instance, choosing the color or frames for hyperlinks. So, you should keep that valuable package in mind. In Chapter 12, Using Hyperlinks and Designing Headings, we shall return to this topic.

On the one hand, hyperref detects many other packages, such as varioref, and can turn their commands into hyperlinks; that’s why we should load hyperref after most other packages. On the other hand, some exceptional packages, such as cleveref, detect hyperref functions and build on them – in such cases, we should load them after hyperref. So, if you combine varioref, cleveref, and hyperref, the package loading order should be as follows:

\usepackage[nospace]{varioref}
\usepackage{hyperref}
\usepackage{cleveref}

The hyperref package manual has a whole section about compatibility with other packages and the required loading order. Open it by entering texdoc hyperref at the command prompt or visit https://texdoc.org/pkg/hyperref. Most of the time, hyperref should be loaded last, with a few exceptions mentioned in the manual.

In this chapter, we discussed how to reference chapters, sections, footnotes, and environments by their number or by the number of the corresponding page.

By using labels and names for referencing, we did not need to specify a number ourselves; LaTeX determines the correct page number, section number, footnote number, or environment number for us.

You also learned some innovative ways to handle context-aware referencing.

In the next chapter, we’ll move on to working with lists, which consist mainly of references: tables of contents, lists of figures and tables, and bibliographies.