[Tex/LaTex] How to center one node exactly between two others with TikZ

nodestikz-pgf

How can I center a TikZ node exactly between two others?

Hypothetically,

\node (a) {a}
\node (c) [right of=c] {c}
\node (b) [between={a,c}] {b}

Best Answer

My suggestion is to use the calc library (see the pgfmanual 13.5 Coordinate Calculations - version October 25, 2010).

An example:

\documentclass{article}   
\usepackage{tikz}
\usetikzlibrary{calc}

\begin{document}
\scalebox{4}{
\begin{tikzpicture}[text height=2ex]
\node (a) {a};
\node (c) [right of=a] {c};
\node (b) at ($(a)!0.5!(c)$) {b};
\end{tikzpicture}
}
\end{document}

The result:

enter image description here

Notice that the syntax you used is wrong: each node should end with ; and the node c can not be positioned at its right.

Notice that without specifying the text height, the nodes are not vertically aligned:

\documentclass{article}   
\usepackage{tikz}
\usetikzlibrary{calc}

\begin{document}
\scalebox{4}{
\begin{tikzpicture}
\node (a) {a};
\node (c) [right of=a] {c};
\node (b) at ($(a)!0.5!(c)$) {b};
\end{tikzpicture}
}
\end{document}

enter image description here

See as reference Problem with TikZ and vertical alignment of text inside nodes.

The calc library, however, is not the only way to proceed. In his comment percusse suggested another approach:

\documentclass{article}   
\usepackage{tikz}

\begin{document}
\scalebox{4}{
\begin{tikzpicture}[text height=2ex]
\node (a) {a};
\node (c) [right of=a] {c};
\path (a) -- (c) node[midway] (b) {b};
\end{tikzpicture}
}
\end{document}

and I see even one more (ok, is not so convenient, but I report it for the sake of completness). Suppose you are using the positioning library and nodes are placed on grid; then for sure the node distance is set in some way so one could go as follows:

\documentclass{article}   
\usepackage{tikz}
\usetikzlibrary{positioning}
\pgfmathtruncatemacro\distance{1}

\begin{document}
\scalebox{4}{
\begin{tikzpicture}[text height=2ex, on grid]
\node (a) {a};
\node (c) [right=\distance cm of a] {c};
\node (b) [right=0.5\distance cm of a]{b};
\end{tikzpicture}
}
\end{document}

Both approaches lead to the result shown in the first example picture.