[Tex/LaTex] Tikz fit-library vs fill (overlaying nested node colors)

colornestingtikz-pgf

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}%

Best Answer

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}

enter image description here