Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

How can I use color in a mathematical expression without losing horizontal spacing?

enter image description here

\documentclass{article}
\usepackage{xcolor}
\definecolor{red}{HTML}{dd0000}
\begin{document}
\[3+(-5)-2+3\]
\[3+(-5){\color{red}-2}+3\]
\end{document}
share|improve this question
1  
as egreg said you can use \mathbin or if you know the argument is a single character you can look up its existing type from its \mathcode and insert the appropriate \mathxx command automatically, see for example tex.stackexchange.com/questions/101699/… –  David Carlisle Mar 13 '13 at 11:21
add comment

2 Answers

up vote 6 down vote accepted

You lose the horizontal spacing because of the brace group {}. Besides egreg's solution there are two ways that don't require telling TeX the kind of object you want:

  1. Use \begingroup ... \endgroup instead of {...},

  2. Use \color{black} to switch back to black.

Both yields the same result:

output

\documentclass{article}
\usepackage{amsmath} % for gather
\usepackage{xcolor}
\definecolor{red}{HTML}{dd0000}
\begin{document}
\begin{gather*}
3+(-5)-2+3 \\
3+(-5) \color{red} -2 \color{black} +3 \\
3+(-5)\begingroup\color{red}-2\endgroup+3
\end{gather*}
\end{document}
share|improve this answer
add comment

You have to work a bit harder, telling TeX the kind of object you want:

\documentclass{article}
\usepackage{xcolor}
\definecolor{red}{HTML}{dd0000}
\begin{document}
\[3+(-5)-2+3\]
\[3+(-5)\mathbin{\textcolor{red}{-}}\textcolor{red}{2}+3\]
\end{document}

For a one shot application this is probably the easiest way. If the emphasis color is always the same, you could define a new command:

\newcommand{\mathem}[2][\mathord]{%
  #1{\textcolor{red}{#2}}}

and input the above as

3 + (-5) \mathem[\mathbin]{-} \mathem{2} + 3

enter image description here

share|improve this answer
    
Very good! Thank you! –  Jostein Trondal Mar 13 '13 at 11:22
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.