Customize Cross Reference Format in LaTeX Using cleveref Package

Nov. 28, 2023

In LaTeX, it’s very convenient to use \label and \ref command to make a cross reference. However, in the normal case, \ref command can’t create a link that can make PDF file jump to the label where it is defined when we click it, and also can’t color the text. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
\documentclass{article}
\usepackage{geometry}
\geometry{a4paper}
\usepackage{graphicx,subfig,amsmath}
\usepackage[x11names]{xcolor}
\pagecolor{AntiqueWhite1}

\DeclareSubrefFormat{myparens}{#1-(#2)}
\captionsetup[subfloat]{subrefformat=myparens}

\begin{document}

\section{Introduction}
\label{sec-introduction}
\begin{equation}
	a = b+c \label{eq}
\end{equation}
\begin{figure}
	\def\CE{0.30}
	\centering
	\subfloat[]{\includegraphics[height=\CE\textwidth, width=\CE\textwidth]{lion.eps}\label{fig-a}}\hspace{20pt}
	\subfloat[]{\includegraphics[height=\CE\textwidth, width=\CE\textwidth]{lion.eps}}
	\caption{This is caption.}
	\label{fig}
\end{figure}

\noindent
Section: ~\ref{sec-introduction}\\
Equation: $~\eqref{eq}$\\
Figure: ~\ref{fig}\\
Subfigure: ~\subref*{fig-a}\\

\end{document}

image-20250107151643090

We can combine using hyperref and cleveref packages12 to overcome the above two problems:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
\documentclass{article}
\usepackage{geometry}
\geometry{a4paper}
\usepackage{graphicx,subfig,amsmath}
\usepackage[x11names]{xcolor}
\pagecolor{AntiqueWhite1}

\usepackage[colorlinks,linkcolor=red]{hyperref}
\usepackage{cleveref}

\DeclareSubrefFormat{myparens}{#1-(#2)}
\captionsetup[subfloat]{subrefformat=myparens}

\begin{document}

\section{Introduction}
\label{sec-introduction}

\begin{equation}
a = b+c 
\label{eq}
\end{equation}

\begin{figure}
	\def\CE{0.30}
	\centering
	\subfloat[]{\includegraphics[height=\CE\textwidth, width=\CE\textwidth]{lion.eps}\label{fig-a}}\hspace{20pt}
	\subfloat[]{\includegraphics[height=\CE\textwidth, width=\CE\textwidth]{lion.eps}}
	\caption{This is caption.}
	\label{fig}
\end{figure}

\noindent
Section: ~\cref{sec-introduction}\\
Equation: $~\cref{eq}$\\
Figure: ~\cref{fig}\\
Subfigure: ~\cref{fig-a}\\

\end{document}

image-20250107151756233

In the above case, the name for equation, eq., is italic. This is because I put ~\cref{eq} in an inline math environment. Otherwise:

1
2
3
4
5
% ...

Equation: ~\cref{eq}\\

% ...

image-20250107154956683

Besides the default setting, there are some other options acceptable for the cleveref package, such as nameinlink:

1
\usepackage[nameinlink]{cleveref}

image-20250107155049890

and noabbrev and capitalise options:

1
\usepackage[nameinlink,noabbrev,capitalise]{cleveref}

image-20250107155131404


References