# Tikz fit-library vs fill (overlaying nested node colors)

I am trying to figure out the best way of nesting tikz nodes having a different background color. I would like the "inner" nodes to "win" concerning the background color. Currently the "outer" node ("fit") always "wins". Is there maybe a better way to aproach this?

A simple example: Nesting an inner node with background color red within an outer node with background color blue:

\documentclass{minimal}
\usepackage{tikz}
\usetikzlibrary{fit}
\begin{document}
% \begin{tikzpicture}%
%   \node (inner) [draw] {foo-inner};%
%   \node (outer) [draw,fit=(inner)] {};%
% \end{tikzpicture}%
% \begin{tikzpicture}%
%   \node (inner) [draw,fill=red] {foo-inner};%
%   \node (outer) [draw,fit=(inner)] {};%
% \end{tikzpicture}%
\begin{tikzpicture}%
\node (inner) [draw,fill=red] {foo-inner};%
\node (outer) [draw,fill=blue,fit=(inner)] {};%
\end{tikzpicture}%
\end{document}%

-
One way would be to add fill opacity as in \node (outer) [draw,fill=blue,fit=(inner),fill opacity=0.5] {};, or simply reverse the order. –  Peter Grill Jan 22 '12 at 23:30

You can also try to send the fitting node to the background layer

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{fit,backgrounds}
\begin{document}
\begin{tikzpicture}%
\node (inner) [draw,fill=red] {foo-inner};%
\node (inner2) [draw,fill=green] at (2,2) {foo-inner2};%
\begin{scope}[on background layer]
\node (outer) [draw,fill=blue,fit=(inner) (inner2)] {};%
\end{scope}
\end{tikzpicture}%
\end{document}


-

## Note that this is more of hack:

If you reverse the order this "appears" (see Note below) to yield desired results:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{fit}
\begin{document}
\begin{tikzpicture}%
\node (inner) [draw,fill=red,fill] {foo-inner};%
\node (outer) [draw,fill=blue,fit=(inner)] {};%
\end{tikzpicture}%
\begin{tikzpicture}%
\node (outer) [draw,fill=blue,fit=(inner)] {};%
\node (inner) [draw,fill=red,fill] {foo-inner};%
\end{tikzpicture}%
\end{document}%


## Note:

As Jake correctly points out the above solution works only because the first tikzpicture. So, just reversing the order won't work in general. But, you could repeat the node you want at the top:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{fit}
\begin{document}
\begin{tikzpicture}%
\node (inner) [draw,fill=red,fill] {foo-inner};%
\node (outer) [draw,fill=blue,fit=(inner)] {};%
\node (inner) [draw,fill=red,fill] {foo-inner};%
\end{tikzpicture}%
\end{document}%

-
Hm, I think the second example only works because you have the first example in the same document. Try changing the text of the inner node in the second example to something longer, or removing the first tikzpicture. –  Jake Jan 22 '12 at 23:40
@Jake: Thank you so much for pointing this out. Wondering if I should delete this. –  Peter Grill Jan 23 '12 at 1:49