3

I have 2 rectangles and an operator between them, the one on the right is longer than the one on the left:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}
\node[rectangle, draw, text width={1cm},  minimum height={1cm}, text centered] (l) {l};
\node (op) [right=0.5cm of l] {$+$};
\node[rectangle, draw, text width={1cm},  minimum height={3cm}, text centered, right=0.5cm of op] (r) {r};
\end{tikzpicture}
\end{document}

The code above makes the two rectangles center adjusted horizontally, does anyone know how to make them top adjusted horizontally?

Martin Scharrer
  • 262,582
SoftTimur
  • 19,767

2 Answers2

5

The alignment of the operator is also very important here, because you want to align it to the left part and then align the right part to it.

One way to do this is to use below right with a zero vertical value and then use the north east anchor to get some top alignment:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}
\node[rectangle, draw, text width={1cm},  minimum height={1cm}, text centered] (l) {l};
\node (op) [below right=0cm and 0.5cm of l.north east] {$+$};
\node[rectangle, draw, text width={1cm},  minimum height={3cm}, text centered, below right=0cm and 0.5cm of op.north east] (r) {r};
\end{tikzpicture}
\end{document}

Result

You can then adjust the operator's vertical position by changing the vertical amount, e.g. turn 0cm to 0.25cm. The vertical amount for the right part must be then negated.

For example:

\node (op) [below right=0.25cm and 0.5cm of l.north east] {$+$};
\node[rectangle, draw, text width={1cm},  minimum height={3cm}, text centered, below right=-0.25cm and 0.5cm of op.north east] (r) {r};

gives:

Result 2

Martin Scharrer
  • 262,582
5

Not so nice as Martin's answer but it works.

First place rectangular nodes aligned to top and after that draw your operator:

\documentclass{standalone}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\node[rectangle, draw, text width={1cm},  minimum height={1cm}, text centered] (l) {l};
\node[rectangle, draw, text width={1cm},  minimum height={3cm}, text centered, anchor=north west] (r) at ([xshift=1cm]l.north east) {r};
\path (l.east) -- (r.west|-l.east) node[midway] (op){$+$};
\end{tikzpicture}
\end{document}

enter image description here

Ignasi
  • 136,588
  • Actually quite nice. The last path line could also be \path (l.east) -| (r.west) node[pos=.25] (op){$+$};, because the pos=.25 for -| or |- is always the middle of the first segment. – Martin Scharrer Oct 17 '11 at 11:14