# How to give any figure a caption based on its horizontal size?

I have figures in both portrait and landscape and of various sizes. I'm trying to find a leeway to give any figure a caption based on its horizontal size. In my thesis.cls file, I've already set a general form as \usepackage[centerlast,small,sc,bf]{caption} and \setlength{\captionmargin}{20pt}. Is there a smart way to do that?

-
Can you clarify a bit what you want? Is it that you want the width of the caption to be dependent on the width of the figure? –  Alan Munn Apr 12 '11 at 21:15
Since you have some responses below that seem to answer your question, please consider marking one of them as ‘Accepted’ by clicking on the tickmark below their vote count. This shows which answer helped you most, and it assigns reputation points to the author of the answer (and to you!). –  Joseph Wright Jul 1 '11 at 21:27

Yes, there is. Use the floatrow package and its \ffigbox command. (This package cooperates well with the caption package.)

\documentclass{article}

\usepackage[centerlast,small,sc,bf]{caption}
\setlength{\captionmargin}{20pt}

\usepackage{floatrow}

\begin{document}

\begin{figure}
\ffigbox[\FBwidth]{%
\rule{8cm}{4cm}%
}{%
\caption{Hello, here is some text without a meaning.}%
}%
\end{figure}

\begin{figure}
\ffigbox[\FBwidth]{%
\rule{4cm}{8cm}%
}{%
\caption{Hello, here is some text without a meaning.}%
}%
\end{figure}

\end{document}


-

Alternatively, savebox can be used in order to avoid using floatrow, such as

\documentclass{article}

\usepackage[centerlast,small,sc,bf]{caption}
\setlength{\captionmargin}{20pt}

\newsavebox\mybox
\newlength\myboxlen

\newcommand{\figcap}[2]{%
\sbox\mybox{#1}
\settowidth{\myboxlen}{\usebox{\mybox}}
\centering
\usebox\mybox
\hskip \textwidth
\parbox{\myboxlen}{#2}
}

\begin{document}

\begin{figure}
\figcap{%
\rule{8cm}{4cm}%
}{%
\caption{Hello, here is some text without a meaning.}%
\label{fig:label1}%
}
\end{figure}

\begin{figure}
\figcap{%
\rule{4cm}{8cm}%
}{%
\caption{Hello, here is some text without a meaning.}%
\label{fig:label2}%
}
\end{figure}

\end{document}


which produce the same thing as above.

-