# Avoid addition of spaces when using colorbox in equations

Colorbox adds some spaces when I use it in equations. E.g. in

\documentclass[12pt]{article}
\usepackage{xcolor}

\begin{document}

\colorbox{yellow}{${a^2}+b^2=c^2$}
\colorbox{yellow}{$\colorbox{blue}{$a^2$}+b^2=c^2$}

\end{document}


the second equation is longer than the first (just taking into account the mathematical symbols). Is there a way to prevent this? Note that I do not mind that the size of the boxes is larger than the enclosed symbols and that the boxes could overlap symbols which are not enclosed if no spaces are added. Note also that I would like to avoid adding negative spaces by hand.

-
–  Peter Grill Apr 10 '12 at 16:52
Besides @DavidCarlisle's answer you might also want to have a look at \mathstrut, which is useful to ensure that the various boxes are the same size. –  Peter Grill Apr 10 '12 at 16:53

## 2 Answers

The padding is \fboxsep:

\documentclass[12pt]{article}
\usepackage{xcolor}

\fboxsep0pt

\begin{document}

\colorbox{yellow}{${a^2}+b^2=c^2$}

\colorbox{yellow}{$\colorbox{blue}{$a^2$}+b^2=c^2$}

\end{document}


Or perhaps you meant something more like this:

\documentclass[12pt]{article}
\usepackage{xcolor}

\def\mycolorbox#1#2{\kern-\fboxsep{\colorbox{#1}{#2}\kern-\fboxsep}}

\parskip\baselineskip

\begin{document}

a \mbox{${a^2}+b^2=c^2$} b

a \colorbox{yellow}{${a^2}+b^2=c^2$} b

{\fboxsep0pt a \colorbox{yellow}{$\colorbox{blue}{$a^2$}+b^2=c^2$} b}

a \mycolorbox{yellow}{$\mycolorbox{blue}{$a^2$}+b^2=c^2$} b

\end{document}

-
Can I change the size of the visible box and its size used for the typesetting independently so that I actually get the effect I described above in my first Note ...? –  highsciguy Apr 10 '12 at 17:14
Oh I thought that was the effect you meant, added a different version to the answer. –  David Carlisle Apr 10 '12 at 17:33

A slightly different approach to David's answer, which shows alignment with your original equation and some different spacing:

\documentclass[12pt]{article}
\usepackage{xcolor}% http://ctan.org/pkg/xcolor
\begin{document}
\colorbox{yellow!80}{${a^2}+b^2=c^2$} \par
{\setlength{\fboxsep}{0pt}
\colorbox{orange!50}{\setlength{\fboxsep}{3pt}$\colorbox{blue!30}{$a^2$}+b^2=c^2$}}

\colorbox{yellow!80}{${a^2}+b^2=c^2$} \par
{\setlength{\fboxsep}{0pt}
\colorbox{orange!50}{\setlength{\fboxsep}{3pt}$\colorbox{blue!30}{$a^2$}\hspace*{-\fboxsep}+b^2=c^2$\hspace*{\fboxsep}}}
\end{document}​


In both examples, the \fboxsep of the outer \colorbox is set to 0pt, letting the coloured a^2 set the height of the resulting (yellow!80) \colorbox. The right end is adjusted to correct for the loss of \fboxsep.

The default \fboxsep is 3pt. Using whitespace set as \fboxsep is better than using 3pt explicitly.

-