[Tex/LaTex] Frame and background color for all figures

colorfloatsframed

I want to have all my figure floats framed all through the text something like those in Wikipedia pages. A pale-coloured (grey) frame and very pale background too. I am using caption package to customize caption fonts as you can see below:

\usepackage[svgnames]{xcolor}
\DeclareCaptionFont{fontstyle}{\fontfamily{phv}\fontseries{mc}\selectfont}
\usepackage[width=0.8\textwidth ,font={small,fontstyle},labelfont={color=
{DodgerBlue},bf,up}, labelsep=period, format=plain]{caption}

I hope I was clear enough.
Thanks

Best Answer

Here you go.

\documentclass{article}
\usepackage{xcolor}
\usepackage{mdframed}
\usepackage{lipsum}

\let\originalfigure=\figure
\let\endoriginalfigure=\endfigure

\renewenvironment{figure}[1][]{
  \begin{originalfigure}[#1]
    \begin{mdframed}[linecolor=black!30,backgroundcolor=black!5]
}{
    \end{mdframed}
  \end{originalfigure}
}


\begin{document}

\begin{figure}[t]
  \centering
  \parbox{10cm}{\lipsum*[1]}
  \caption{Foo}
\end{figure}

\begin{figure}[b]
  \centering
  \parbox{10cm}{\lipsum*[2]}
  \caption{Bar}
\end{figure}

\lipsum[3]

\end{document}

enter image description here

NB. In a previous version of this answer, I defined a shadedfigure environment, which had to be used as an alternative to the figure environment. In this latest version, I use a trick discussed in "Duplicating Environments" to replace the figure environment. Therefore, this solution will now add frames and background colours to all figures throughout the entire document.

Related Question