[Tex/LaTex] Overlay specification with beamer and ‘\colorbox’

beamercolorboxoverlays

I use \colorbox in my slides to highlight part of the text (as if it was highlighted with a marker). The command also accepts beamer overlay specifications (e.g. \colorbox<1>{yellow}{Text}). However, strangely enough on the slides that does not match the overlay specification the text is replaced by a purely black rectangle. More specifically, colorbox<1>{yellow}{Text} produces "Text" with yellow background on slide 1 and on the following slides produces a black rectangle (as if it was generated by \colorbox{black}{Text}). Any ideas on why this is happening and how can be fixed?

Many thanks,


Here is a MWE:

\documentclass{beamer}
\begin{document}
\begin{frame}
\centering
\colorbox<1>{yellow}{Text}

\onslide<2->{Some other text}
\end{frame}
\end{document}

And here are the first and second slides resulted from the above example:
Slide 1
Slide 2

Best Answer

You could redefine \colorbox:

\renewcommand<>\colorbox[2]{\only#3{\beameroriginal\colorbox{#1}{#2}}}

But maybe it is better to define a new command:

\newcommand<>\hlbox[2]{\only#3{\colorbox{#1}{#2}}}

Example

\documentclass{beamer}
\newcommand<>\hlbox[2]{\only#3{\colorbox{#1}{#2}}}
\begin{document}
\begin{frame}
\centering
\hlbox<1>{yellow}{Text}
\par
Text
\par
\onslide<1-2>{Some other text}
\end{frame}
\end{document}

enter image description here


If you want something like

enter image description here

you could use

\documentclass{beamer} 
\newcommand<>\highlightbox[2]{%
  \alt#3{\makebox[\dimexpr\width-2\fboxsep]{\colorbox{#1}{#2}}}{#2}%
}
\begin{document}
\begin{frame}{Some Fancy Title}
\centering
Text \highlightbox<2>{yellow}{Text} Text
\par
Text Text Text
\end{frame}
\end{document}