6

I want to create a style in TikZ that draws a node with a label in the above left corner.

The problem is, that the label text and the node width should be variable. Below is a minimal example (my current approach), where the position of the label of the last node (nodename3) is incorrect:

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

\begin{document}
\begin{tikzpicture}
    \tikzset{genericnode/.style={rectangle, rounded corners=2pt, draw=black},
             mystyle/.style={genericnode, text width=15mm, fill=red!50,
                             label={[anchor=west, yshift=3pt, xshift=-9mm]{\tiny #1}}},
             vll/.style={mystyle=VeryLongLabel},
             sl/.style={mystyle=ShortL},}

    \node[vll]                                           (nodename)  {\tt text};
    \node[sl, below = 1cm of nodename]                   (nodename2) {\tt node with more lines};
    \node[sl, below = 1cm of nodename2, text width=35mm] (nodename3) {\tt node with more lines};
\end{tikzpicture}
\end{document}

enter image description here

Can you give me a hint?

4

You could set an alias name for the main node and use this name in the label options to position the label node:

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

\begin{document}
\begin{tikzpicture}
  \tikzset{
    genericnode/.style={rectangle, rounded corners=2pt, draw=black,},
    mystyle/.style={
      genericnode, text width=15mm, fill=red!50,
      alias=genericnode,% <- alias added
      label={[anchor=south west,shift={(genericnode.north west)},inner sep=2pt]{\tiny #1}}% position the label using the alias 
    },
    vll/.style={mystyle=VeryLongLabel},
    sl/.style={mystyle=ShortL},}

  \node[vll] (nodename) {\texttt{text}};
  \node[sl, below = 1cm of nodename] (nodename2) {\texttt{node with more lines}};
  \node[sl, below = 1cm of nodename2, text width=35mm] (nodename3) {\texttt{node with more lines}};
\end{tikzpicture}
\end{document}

Result:

enter image description here

  • I guess node contents for both is also an option. – percusse Jul 26 '17 at 20:22

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.