How to color math symbols?

\textcolor from the xcolor package also works in mathmode, even if the name says otherwise. You can also use $ \color{<color>} C^2 $. It sets the color for the rest of the current scope (group).

Examples:

\documentclass{article}

\usepackage{xcolor}

\begin{document}

$ \color{red} C^2 $

$ \color{yellow} A = \textcolor{blue}{B} \mathbin{\textcolor{red}{-}} \textcolor{green}{C} $

\end{document}

enter image description here

Note that the \mathbin must be wrapped around the coloured, binary - here, as Leo Liu pointed out in his comment, to set the correct spacing again. The coloring changes the math type so they spacing would be different.


An addition to Martin Scharrer's answer.

\textcolor has a side effect in math, that the contents is put in curly braces (see definition of \@textcolor). The color implementation of package color is based on groups (the color is restored at the end of the group automatically), but curly braces also make a subformula in math. This affects the horizontal spacing, since the \textcolor now acts as ordinary math atom. This can be avoided by using \begingroup and \endgroup instead of the curly braces:

\documentclass{article}

\usepackage{xcolor}% or package color

\begin{document}

\[
  \color{yellow} A
  \begingroup\color{magenta}=\endgroup
  \textcolor{blue}{B}
  \mathbin{\color{red}-}% shorter than \mathbin{\textcolor{red}{-}}
  \textcolor{green}{C}
  \begingroup\color{cyan}+\endgroup
  D
\]
\end{document}

Result

A macro \mathcolor can be defined, which can be used instead of \textcolor in math:

\documentclass{article}

\usepackage{xcolor}

\makeatletter
\def\mathcolor#1#{\@mathcolor{#1}}
\def\@mathcolor#1#2#3{%
  \protect\leavevmode
  \begingroup
    \color#1{#2}#3%
  \endgroup
}
\makeatother

\begin{document}

\[
  \color{yellow} A
  \mathcolor{magenta}{=}
  \mathcolor{blue}{B}
  \mathcolor{red}{-}
  \mathcolor{green}{C}
  \mathcolor{cyan}{+}
  D
\]
\end{document}

Or the definition of \textcolor can be fixed:

\makeatletter
\renewcommand*{\@textcolor}[3]{%
  \protect\leavevmode
  \begingroup
    \color#1{#2}#3%
  \endgroup
}
\makeatother