[Tex/LaTex] How to set width of caption to width of figure

captionsfloats

How can I set the width of the caption to be the same as the width of the pic when I give a height of a picture and have the width deduced automatically by aspect ratio?

\begin{figure}
  \includegraphics[height=10cm]{pic.png}
  \caption{My very long caption ....}
\end{figure}

In this case the pic is on the left (let's assume only 12cm wide) and the caption is running over the complete text width.

Best Answer

You need to store the image in a savebox and then wrap the caption into a minipage with the width of the box.

\documentclass{article}
\usepackage{graphicx}
\newsavebox\mysavebox

\usepackage{lipsum} % for example text only
\begin{document}

\lipsum

\begin{figure}
  \centering
  \sbox\mysavebox{\includegraphics[height=5cm]{example-image}}%
  \usebox\mysavebox
  \par
  \begin{minipage}{\wd\mysavebox}
  \caption{My very long long long long long long long long long long long long long long long long long long long caption }
  \end{minipage}
\end{figure}

\lipsum

\end{document}

enter image description here


The adjustbox package simplifies this approach and also avoids "bad box" warnings if the image is larger then the usual text width.

\documentclass{article}
\usepackage{graphicx}
\usepackage{adjustbox}
\newlength\mylength

\usepackage{lipsum}
\begin{document}

\lipsum

\begin{figure}
\adjustimage{height=5cm, gstore width=\mylength, center}{example-image}
%alternative: \adjustbox{gstore width=\mylength,center}{\includegraphics[height=10cm]{example-image}}
\par% or empty line, needed to get caption below the image, not to the rigth
\adjustbox{minipage=\mylength,center}{\caption{My very long long long long long long long long long long long long long long long long long long long caption }}
\end{figure}

\lipsum

\end{document}
Related Question