[Tex/LaTex] ny AMS TeX or LaTeX macro for background color in math-mode

amsmathcolor

Is there any way to display math expressions with a background color (highlight) using AMS-Tex or AMS-LaTeX . For example, using AMS-TeX/LaTeX, we can display a math expression in font color using \color[colorName]{mathExpression}.

UPDATE Using the answer from @werner, I tried $\frac{\colorbox{yellow}{$a-b$}}{c-d}$ to highlight only the numerator but the size of a-b is much larger than the demominator c-d even with the setting of \setlength{\fboxsep}{1pt} -in the preamble – as shown below. How can I get the desired output shown below:

enter image description here

Best Answer

If you load xcolor, you can use \colorbox. This uses a regular "framed box", so you can set the values of \fboxsep to decrease the border.

In most cases, text-related formatting of this sort also transfers to math-related content. However, a verbatim switch is sometimes required since boxing reverts back to text mode. As such, use

\colorbox{<color>}{$<math content>$}

and not

$\colorbox{<color>}{<math content>}$

Here's a small example in LaTeX illustrating the use of \colorbox together with a modification of \fboxsep:

enter image description here

\documentclass{article}
\usepackage{xcolor}% http://ctan.org/pkg/xcolor
\setlength{\parindent}{0pt}% Just for this example
\begin{document}
Here is \colorbox{blue!50}{coloured text} with a coloured \colorbox{green!30}{$f(x)$} function. \par \bigskip
\setlength{\fboxsep}{2pt}% No "border" around coloured box
Here is \colorbox{blue!50}{coloured text} with a coloured \colorbox{green!30}{$f(x)$} function. \par
\end{document}