3

I have two pgf fitting nodes:

  • one below the other,
  • left aligned,
  • with different (unpredictable) widths,

and I'd like them be backgrounded, with backgrounds of the same width.

For this, I got help from Creating a node fitting the horizontal width of two other nodes but I encounter a trouble pointed out by the following MWE: the background of the second node with minimum width equal to the first one's is horizontally shifted.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning,calc,backgrounds,fit}
\begin{document}
\tikzstyle{every node}=[font=\ttfamily]
\begin{tikzpicture}
  \node (n11)                            {x};
  \node (n12) [right=of n11,xshift= 5mm] {x};
  \node (n21) [below=of n11,yshift=10mm] {x};
  \node (n22) [right=of n21]             {x};
  \begin{pgfonlayer}{background}
    \node[
        fill=red!20,
        inner sep=0pt,
        fit=(n11) (n12)
        ] (n1) {};
    \path let
        \p1=(n1.west),
        \p2=(n1.east)
    in node [
        fill=blue!20,
        inner sep=0pt,
        fit=(n21) (n22),
        minimum width=\x2-\x1-\pgflinewidth
        ] (n2) {};
  \end{pgfonlayer}
\end{tikzpicture}
\end{document}

Here is the output:

enter image description here

What's going on?

Denis Bitouzé
  • 9,652
  • 4
  • 27
  • 85
  • For n2, you may use fit=(n21) (n22) (n1 |- n21) (n1 |- n21) without minimum width (and add line width=0 to n1 defintion). – Paul Gaborit Oct 17 '14 at 05:51

1 Answers1

2

Here is a possible solution (if I understand the question):

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning,calc,backgrounds,fit}
\tikzset{
  every node/.style={font=\ttfamily}
}
\begin{document}
\begin{tikzpicture}
  \node (n11)                            {x};
  \node (n12) [right=of n11,xshift= 5mm] {x};
  \node (n21) [below=of n11,yshift=10mm] {x};
  \node (n22) [right=of n21]             {x};
  \begin{pgfonlayer}{background}
    \node [fill=red!20 ,inner sep=0pt,fit=(n11)(n12),line width=0] (n1) {};
    \node [fill=blue!20,inner sep=0pt,fit=(n21)(n22)(n1.west |-n21)(n1.east |-n22)] (n2) {};
  \end{pgfonlayer}
\end{tikzpicture}
\end{document}

enter image description here

Denis Bitouzé
  • 9,652
  • 4
  • 27
  • 85
Paul Gaborit
  • 70,770
  • 10
  • 176
  • 283
  • AFAICS, you understood perfectly well and this way of doing is much more elegant! If I'm right, (n1.west |-n21) isn't necessary as (n1) and (n2) are left aligned, isn't it? Could you explain why line width=0 is necessary for (n1) but not for (n2)? – Denis Bitouzé Oct 17 '14 at 15:37
  • 1
    @DenisBitouzé I must define n1 with line width=0 because the second fit operation uses n1. Try line width=1cm to see the difference. – Paul Gaborit Oct 17 '14 at 23:41