[Tex/LaTex] \ref different colors for figures, equations, etc

colorcross-referencing

How can I have different colors for \ref{} for figures and equations? My figures have label \label{fig:name} whereas equations are just \label{name}. Is there a way I can set the color to be different depending on whether the argument has a "fig:"?

Best Answer

Please look for a non-cleveref version at the end of the answer.

The cleveref package allows for versatile configurations of the cross-reference format, with \crefformat{figure}{#2#1#3} where #2 and #3 are reserved for hyperanchor settings and should not be interchanged, whereas #1 contains the content to be typeset, so font switches or \color commands are possible here.

\documentclass{article}
\usepackage{xcolor}
\usepackage{hyperref}
\usepackage{cleveref}


\crefformat{figure}{#2{\color{blue}#1}#3}
\Crefformat{figure}{#2{\color{blue}#1}#3}

\crefformat{equation}{#2{\bfseries\color{violet}#1}#3}
\Crefformat{equation}{#2{\itshape\color{violet}#1}#3}

\begin{document}

See \cref{foofigure} or \cref{fooequation} or \Cref{fooequation}


\begin{figure}
  \caption{foofigure}\label{foofigure}
\end{figure}

\begin{equation}
  E=mc^{2} \label{fooequation}
\end{equation}

\end{document}

enter image description here

Version with the traditional p@figure etc. cross-reference format:

\documentclass{article}
\usepackage{xcolor}
\usepackage{hyperref}

\makeatletter
\def\p@figure{\color{blue}}
\def\p@equation{\itshape\color{violet}}
\makeatother



\begin{document}

See \ref{foofigure} or \ref{fooequation}

\begin{figure}
  \caption{foofigure}\label{foofigure}
\end{figure}

\begin{equation}
  E=mc^{2} \label{fooequation}
\end{equation}

\end{document}

The output is basically the same as in the screen shot from the other version, hyperlink frames are not shown in the image.