# How to prevent label overlapping inside a fit in tikz

I have two nodes fitted inside a fit node. The fit node also has a label. The problem shown by the MWE below: the label is overlapped by the two inner nodes.

Q: How to increase the fit node height above the inner nodes so that the label is 100% visible? I could increase the minimum height of the fit node but it would add padding also below the inner nodes. That I don't want. The inner nodes should be bottom aligned. Extra space/padding is needed only on top of the inner nodes.

Or should I just make the label a separate node, position it above the inner nodes and fit all three together without using the actual label key?

\documentclass[10pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{tikz}
\usetikzlibrary{positioning, backgrounds, fit}

\tikzset{
base/.style = {draw=black, minimum height=2cm},
}

\begin{document}
\begin{tikzpicture}[]
\node (Foo)[base] {Foo};
\node (Bar)[base, right=of Foo] {Bar};

\begin{scope}[on background layer]
\node [draw=black!50, fit=(Foo) (Bar), label={[anchor=north]north:$Long label$}] (Fit) {};
\end{scope}

\draw[->](Foo) -- (Bar);
\end{tikzpicture}

\end{document}


You could write a style, called fit label, that measures the label and extends the fit accordingly. The measurement is done in height("#1"), the fit is moved up by half this distance (plus the usual inner sep) and the bounding box increased by adjusting inner ysep.

\documentclass[10pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{tikz}
\usetikzlibrary{positioning, backgrounds, fit}

\tikzset{
base/.style = {draw=black, minimum height=2cm},
}

\begin{document}
\begin{tikzpicture}[fit label/.style={yshift={(height("#1")+4pt)/2},
inner ysep={(height("#1")+8pt)/2},
label={[anchor=north,font=\itshape]north:#1}}]
\node (Foo)[base] {Foo};
\node (Bar)[base, right=of Foo] {Bar};

\begin{scope}[on background layer]
\node [draw=black!50, fit=(Foo) (Bar),
fit label=Long Text] (Virtual) {};
\end{scope}

\draw[->](Foo) -- (Bar);
\end{tikzpicture}

\end{document}


Alternatively you could make the fit larger (by hand).

\documentclass[10pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{tikz}
\usetikzlibrary{positioning, backgrounds, fit}

\tikzset{
base/.style = {draw=black, minimum height=2cm},
}

\begin{document}
\begin{tikzpicture}[]
\node (Foo)[base] {Foo};
\node (Bar)[base, right=of Foo] {Bar};

\begin{scope}[on background layer]
\node [draw=black!50, fit={(Foo) (Bar) ([yshift=1em]Foo.north)},
label={[anchor=north,font=\itshape]north:Virtual Machine}] (Virtual) {};
\end{scope}

\draw[->](Foo) -- (Bar);
\end{tikzpicture}

\end{document}

• Thanks for providing both the "manual" way and the one which calculates the height automatically. Worked perfectly! – Paapaa Jul 13 '19 at 8:02
• @Paapaa You're welcome! – user121799 Jul 13 '19 at 8:08