[Tex/LaTex] How to set a background color of figure environment

colorfloats

Currently I've this situation:

\newenvironment{inline}[2]{
  \begin{figure}[h!]
    \caption{#1}\label{#2}
    \vspace{10pt}%
}{
  \end{figure}
}

How can I set a background color to whole content, which is in the figure?

Best Answer

You can use the mdframed package for this. In the below MWE, I've added an option first argument to the inline environment which specifies the backgroundcolor (default is black!25 = 25% black):

enter image description here

\documentclass{article}
\usepackage{lipsum}% http://ctan.org/pkg/lipsum
\usepackage{mdframed}% http://ctan.org/pkg/mdframed
\usepackage{xcolor}% http://ctan.org/pkg/xcolor
\newenvironment{inline}[3][black!25]{
  \begin{figure}[h!]
    \begin{mdframed}[backgroundcolor=#1]
    \centering\caption{#2}\label{#3}
    \vspace{10pt}%
}{%
    \end{mdframed}
  \end{figure}
}
\begin{document}
\lipsum[1]
\begin{inline}{An image}{image}
  \rule{150pt}{100pt}
\end{inline}
\lipsum[2]
\end{document}

I've only added the backgroundcolor option to mdframed, leaving all the other settings as is (for example, it includes a border). Read the mdframed documentation on how to modify any default settings.

Having a caption above the figure, you may be interested in adjusting the lengths \abovecaptionskip and \belowcaptionskip to suit your needs - they are set with the caption-below-float in mind. The defaults are 10pt and 0pt, respectively, in the standard document classes.

In the above MWE, xcolor provides the colour specification, while lipsum provided some dummy text, Lorem Ipsum style.

Related Question