[Tex/LaTex] \colorbox{color}{text} display issue with same math expressions but different syntax

amsmathcolortcolorbox

My following LaTeX file in MikTeX' TeXworks editor on my Windows 8.1 is showing the highlighted content with different sizes when the highlighted content is inside quadratic formula but not when it's outside the quadratic formula – even though I'm using fboxsep in the preamble of the TeX file. I expected the third display below of the quadratic formula to be of the same size as of the second display.

\documentclass{article}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{color}
\setlength{\fboxsep}{0pt}
\newcommand{\highlight}[1]{\text{\colorbox{yellow}{$#1$}}}
\begin{document}
 This  \(\frac{-b\pm \sqrt{b2- 4ac}}{2a}\) and \(\frac{-b\pm \sqrt{\highlight{b2- 4ac}}}{2a}\) Vs.  \(\frac{-b\pm \sqrt{\colorbox{yellow}{\(b2- 4ac\)}}}{2a}\) is a test. Also a test: \( \sqrt{\colorbox{yellow}{\(b2- 4ac\)}}\) vs \(\sqrt{\highlight{b2- 4ac}}\)
\end{document}

enter image description here

Best Answer

Once you're in the \colorbox, LaTeX forgets that you were in math mode and it forgets the type of font you were using. In math mode there are four different sizes:

\displaystyle
\textstyle
\scriptstyle
\scriptscriptstyle

If you rewrite you third equation as

\(\frac{-b\pm \sqrt{\colorbox{yellow}{\(\scriptstyle b2- 4ac\)}}}{2a}\)

then you'll get the same size script as in the two early versions.

But better than having to guess the font size (and there's more going on when you try to use super/subscripts within the square root), I suggest playing with hf-tikz as in

\documentclass{article}

\usepackage[customcolors]{hf-tikz}

\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}

\usepackage{color}
\setlength{\fboxsep}{0pt}
\newcommand{\highlight}[1]{\text{\colorbox{yellow}{$#1$}}}

\tikzset{set fill color=yellow,
         set border color=yellow,
         disable rounded corners=true}

\begin{document}

 This \(\frac{-b\pm \sqrt{b^2- 4ac}}{2a}\) 
  and \(\frac{-b\pm \sqrt{\highlight{b^2- 4ac}}}{2a}\) 
  Vs. $\frac{-b\pm \sqrt{%%
    \tikzmarkin{A}(0,1ex)(0,-0pt)
      b^2- 4ac
    \tikzmarkend{A}}}{2a}\) is a test. Also a test: 
      \( \sqrt{\colorbox{yellow}{\(b2- 4ac\)}}\) 
  vs  \(\sqrt{\highlight{b2- 4ac}}\)

\end{document}

enter image description here

Related Question