# Overlay specification with beamer and '\colorbox'

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:

• Could you show a Minimum working (or not) example? From \documentclass to \end{document. – Ignasi May 22 '17 at 9:37
• @Ignasi Done :-)! – kMaster May 22 '17 at 10:09

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}

If you want something like

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}
• Thanks so much. In fact I ended up with writing something similar to your second proposition manually everywhere. Your idea of defining a new command is much more efficient. – kMaster May 22 '17 at 12:22
• P.S. I guess the order of \makebox and \colorbox should be reversed in your version of \highlightbox. Otherwise, the highlight gets extended to adjacent characters if for example you only highlight a letter in a word. – kMaster May 22 '17 at 12:39

I think in your code, the colorbox is set to yellow only on frame 1, but to black (maybe the standard value?) on all other frames. Including an extra only around the colorbox made sure that it's only displayed on frame 1.

I tried removing the overlay specification (<1>) from the colorbox, since it seemed redundant. The code compiles, but the text is moved towards the left...

\documentclass{beamer}
\begin{document}
\begin{frame}
\centering
\only<1>{\colorbox<1>{yellow}{Text}}
\onslide<2->{Some other text}
\end{frame}
\end{document}