1
\documentclass[10pt]{beamer}
% \usetheme[progressbar=frametitle]{metropolis}
\begin{document}

\begin{frame}
\frametitle{Test}
\begin{itemize}[<+->]
    \item A
    \item B
    \item C
\end{itemize}

\only<1>{\hfill\includegraphics[width=0.5\textwidth]{example-image-a}\hfill}%
\only<2>{\hfill\includegraphics[width=0.5\textwidth]{example-image-b}\hfill}%

\end{frame}
\end{document}

How do I center the images when in \only? The second \hfill doesn't seem to have any effect.

I also tried \hfills outside the \only, but that didn't work as well.

hfill not working with only

ksgj1
  • 637

2 Answers2

2

Use \begin{center} and \end{center} in place of the \hfills inside the \onlys, like so:

\only<1>{\begin{center}\includegraphics[width=0.5\textwidth]{example-image-a}\end{center}}%
\only<2>{\begin{center}\includegraphics[width=0.5\textwidth]{example-image-b}\end{center}}%

(Alternatively, you can wrap both \onlys in one set of \begin{center} and \end{center}s.

\begin{center}
\only<1>{\includegraphics[width=0.5\textwidth]{example-image-a}}%
\only<2>{\includegraphics[width=0.5\textwidth]{example-image-b}}%
\end{center}

Note that \centering is not recommended in this context (When should we use \begin{center} instead of \centering?) and would center subsequent text.

If you decide to use the figure environment (\begin{figure} and \end{figure}) to encapsulate the \includegraphics', you'd use \centering inside that.

Alex
  • 231
2

Alex gave you already some options for how to center the images. Assuming that you wish to stick to your syntax (in order to avoid the extra vertical space introduced by \begin{center} ... \end{center}, you could just insert a \strut.

\documentclass[10pt]{beamer}
% \usetheme[progressbar=frametitle]{metropolis}
\begin{document}

\begin{frame}
\frametitle{Test}
\begin{itemize}[<+->]
    \item A
    \item B
    \item C
\end{itemize}

\only<1>{\hfill\includegraphics[width=0.5\textwidth]{example-image-a}\hfill\strut}%
\only<2>{\hfill\includegraphics[width=0.5\textwidth]{example-image-b}\hfill\strut}%
\end{frame}
\end{document}

enter image description here

Personally I would actually top-align the content.

\documentclass[10pt]{beamer}
% \usetheme[progressbar=frametitle]{metropolis}
\begin{document}

\begin{frame}[t]
\frametitle{Test}
\begin{itemize}[<+->]
    \item A
    \item B
    \item C
\end{itemize}

\only<1>{\hfill\includegraphics[width=0.5\textwidth]{example-image-a}\hfill\strut}%
\only<2>{\hfill\includegraphics[width=0.5\textwidth]{example-image-b}\hfill\strut}%
\end{frame}
\end{document}

enter image description here