3

I'm trying to make all my figures (including caption) backgrounded with a decent color.

I already found these questions with some nice answers:

But all these answers have in common that they define some new environments or commands that need to be put inside the figures or replace the figures completly.

Is there a way to put a background color behind existing floats without having to change the content of these existing floats?

Foo Bar
  • 13,247

2 Answers2

7

enter image description here

\documentclass{article}

\makeatletter

\def\foo#1\normalcolor\vbox\bgroup#2!!{%
\def\@xfloat ##1[##2]{#1%
 \normalcolor
      \hbox\bgroup{\color{yellow}\leaders\vrule\hskip\columnwidth\hskip-\columnwidth}%
      \vbox \bgroup\aftergroup\egroup
#2}}
\expandafter\foo\@xfloat{#1}[#2]!!

\makeatother

\usepackage{color}
\begin{document}

\begin{figure}
a\\b\\c
\caption{yes no}
\end{figure}

one two three

\end{document}
David Carlisle
  • 757,742
  • Thanks, how do select the float types (figure, table, ...) for which these apply? For example if I want different colors for figures and tables. – Foo Bar Apr 04 '13 at 19:07
  • 1
    \@captype will be figure table etc so you could test that or if it is just a matter of colour choice replace yellow by color-\@captype and then use \definecolor to define colors color-figure and color-table – David Carlisle Apr 04 '13 at 19:10
  • 1
    @DavidCarlisle, what is the meaning of !! on the 3rd line of the code? – Sigur Apr 04 '13 at 23:29
  • 2
    @Sigur It's just a token to mark the end of the argument (the end of the expansion of \@xfloat anything could be used that is not in the expansion of the macro so long as the same marker is used 6 lines later after the expansion of \@xfloat. – David Carlisle Apr 05 '13 at 00:09
3

Here is an elementary implementation using mdframed that redefines the figure environment (therefore not adapting the usage of figure in your document):

enter image description here

\documentclass{article}
\usepackage{lipsum,mdframed,xcolor}% http://ctan.org/pkg/{lipsum,mdframed,xcolor}
\let\oldfigure\figure% Store old figure environment start
\let\endoldfigure\endfigure% Store old figure environment end
\renewenvironment{figure}[1][htbp]% Redefine figure
  {\oldfigure[#1]\mdframed[backgroundcolor=blue!15]}
  {\endmdframed\endoldfigure}
\begin{document}
\lipsum[1]
\begin{figure}[ht]
  \centering\includegraphics{example-image-a}
  \caption{This is a figure}
\end{figure}
\lipsum[2]
\end{document}

From here it would be straight forward to apply a different style to a different float (like table, for example).

Werner
  • 603,163
  • Tried this, too. Worked well, hence the upvote, but I have accepted the other answer because it does not depend on a package (which could possbibly introduce unwanted side effects). – Foo Bar Apr 04 '13 at 19:37