6

I'm struggling to find a way to position a rectangle A above another one B (e.g., by 2cm) while vertically aligning it's right-end with the center of B.

Thanks in advance for your answers.

NS

5
\documentclass[tikz,border=5mm]{standalone}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}
\node [draw,minimum width=3cm,minimum height=2cm] (A) {A};
\node [above=2cm of A,anchor=south west,draw,minimum width=3cm,minimum height=2cm] (B) {B};
\end{tikzpicture}
\end{document}

enter image description here

  • Thank you! I was putting the anchor at the wrong place as I was using the syntax: \node […,anchor=…] (n0) [above=2cm of…] {}; changing to \node […] (n0) [above=2cm of…,anchor=…] {}; worked. – N. Short Apr 11 '18 at 16:38
5

This is one way for doing this, place node A at (B.north) from anchor=south east, then shift A by 2cm upward.

\documentclass[tikz,border=5pt]{standalone}
\begin{document}

\begin{tikzpicture}[minimum width=2cm]
\node(B) [draw] {B};
\node(A) at (B.north) [draw,anchor=south east,yshift=2cm] {A};
\end{tikzpicture}

\end{document}

enter image description here

5
\documentclass[border=2mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
\node[draw, rectangle, minimum width=3cm] (B) {B};
\node[draw, rectangle, minimum width=2cm, anchor=east]
     (A) at ($(B.center)+(0, 2cm)$) {A};   % 2cm between centers of nodes
\end{tikzpicture}


\end{document}

Result

  • Without calc you can use ([yshift=2cm]B) (no need of .center that is by default in this case). – Kpym May 2 '18 at 8:52
4

enter image description here

\documentclass[border=2mm]{standalone}
\usepackage{tikz,luatex85}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
\node[draw, rectangle, minimum width=3cm] (B) {B};
\node[draw, rectangle, minimum width=2cm, anchor=south east,
    yshift=-2cm]
     (A) at (B.center) {A};
\end{tikzpicture}
\end{document}
1

Here two examples using \usetikzlibrary{fit}.

enter image description here

\documentclass[border=4mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{fit}

\begin{document}
  \begin{tikzpicture}
  \node[draw, fit={(0,0) (3,2)}, inner sep=0pt, label=center:K] (A) {};
\end{tikzpicture}


\begin{tikzpicture}
\node[draw, fit={(0,0) (4.5,2)}, inner sep=0pt, label={[anchor=west,inner sep=0pt]west:$P$}] (B) {};
\end{tikzpicture}



\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.