1

Given the following code:

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}
\tikzstyle{block} = [draw, rectangle, minimum height=3.5em, minimum width=4.5em]

\begin{document}
\begin{tikzpicture}
\node [block,align=center](a) {A};
\node [block,align=center,right=1cm of a](b) {B};
\node [block,align=center,below=1cm of a](c) {C};
\end{tikzpicture}
\end{document}

I would like that the C-Block, which is below the A- and B-Block takes automatically the width that the A and B Block span. I would like it to look something like this:

enter image description here

How can I achieve this without manually setting the width of the C-Block?

2 Answers2

3

You can use the calc TikZ library.

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{calc,positioning}
\tikzstyle{block} = [draw, rectangle, minimum height=3.5em, minimum width=4.5em]

\begin{document}
\begin{tikzpicture}
\node [block,align=center](a) {A};
\node [block,align=center,right=1cm of a](b) {B};
\path
  let \p0 = (a.south west),
      \p1 = (b.south east),
      \p2 = ($ (\p0)!.5!(\p1) $)
  in
    node [block, below=1cm of \p2, minimum width=\x1-\x0] (c) {C};
\end{tikzpicture}
\end{document}

The let path command lets you define points via \p{name} = ... and numbers via \n{name} = ... that you can refer to from inside the let operation (here a node). If you have a point like \p0, then you can refer to its components as \x0 and \y0.

For \p2, I used another feature of the calc library, a so-called "partway modifier." (\p0)!.5!(\p1) means the point halfway between \p0 and \p1. The pgf manual has all the details of both of these.

Note that you should probably be using \tikzset rather than \tikzstyle.

TH.
  • 62,639
2

Another solution with a fit node. In this case node contents has to be added as a centered label (as it's explained in section 57: Fitting library)

Sometimes we forget that the fit list of a fitting node is used just to fix its size, but it's position is not restricted to be around fitted nodes.

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning, fit}
\tikzstyle{block} = [draw, rectangle, minimum height=3.5em, minimum width=4.5em]

\begin{document}
\begin{tikzpicture}
\node [block,align=center](a) {A};
\node [block,align=center,right=1cm of a](b) {B};
\node [block, fit= (a) (b), inner sep=-.5\pgflinewidth, below right=1cm and 0 of a.south west, label=center:C](c) {};
\end{tikzpicture}
\end{document}

enter image description here

Ignasi
  • 136,588