[Tex/LaTex] Vertically and horizontally align image inside table

graphicshorizontal alignmenttablesvertical alignment

I have a table with two columns. The first column contains text, the second a image. Short example:

\documentclass{article}
\begin{document}

\begin{table}[htbp]
    \centering
    \caption{My caption}
    \label{tab:mytab}
    \begin{tabular}{|p{1.0cm}|c|}
        \hline
        \textbf{Number}   & \textbf{Images} \\ \hline
        Nr. 1 & \raisebox{.5\totalheight}{\includegraphics[width=0.8\textwidth]{foo}}       \\ \hline
        Nr. 2 & \raisebox{.5\totalheight}{\includegraphics[width=0.8\textwidth]{foo}}       \\ \hline
    \end{tabular}
\end{table}

\end{document}

I want to center the text and image vertically and horizontally. Does anyone know how to do this?

Best Answer

With help of package adjustbox you can obtain:

enter image description here

In the first row the margin above and below picture is added, in the second row the image is without added margins. The code:

\documentclass{article}
\usepackage{graphicx}
\usepackage[export]{adjustbox}

\begin{document}
\begin{table}[htbp]
    \centering
    \caption{My caption}
    \label{tab:mytab}
    \begin{tabular}{|p{1.5cm}|c|}
        \hline
\textbf{Number}   
        &   \textbf{Images} \\ 
        \hline
Nr. 1   &   \includegraphics[width=0.8\textwidth,
                             margin=0pt 1ex 0pt 1ex,valign=m]{example-image}  \\
        \hline
Nr. 2   &   \includegraphics[width=0.8\textwidth,valign=m]{example-image}  \\
        \hline
    \end{tabular}
\end{table}
\end{document}

Addendum: If you like to have horizontally centered contents also in the first table's column, than the following changes are necessary:

  • in preamble to be add \usepackage{array}
  • in table parameters the column type p{...} should be replaced by >{\centering}p{...}