I want to draw with tikz the following:

enter image description here

That is,

abc, then def in green AND surrounded by a red rectangle, and then a ,.

What I have now is three different nodes. But they are not aligned to one another, and the distances between them are rather chosen for arbitrary distances by me, which is not systematic; If I change the font and font size, the distances may need to be amended.

\node at (0,0) (A) {abc,};
\node[draw,color=red,right = 1ex of A] (B) {\textcolor{blue}{def}};
\node[right = 1ex of B] (C) {,};

My output: enter image description here

  • 1
    Try anchor=base or similar things.
    – Symbol 1
    Oct 22, 2022 at 23:32
  • Is there a way to do it with only one node that changes its appearance along the way?
    – tush
    Oct 23, 2022 at 0:14
  • As you have it now, this could be made with one not, color changing inside the text and a colored \fbox. For a more general approach, the subnode from tikzmark. Or separate nodes with one node fitted around it so that you can reference all under one name (and connect lines to it). Why do you need it to be one node? width(" ") of A could be used to get the width of a space. (or you just put a literal space \ as part of the nodes and choose no space between the nodes. Oct 23, 2022 at 0:30
  • base right=of … could help with @Symbol1's tip. Oct 23, 2022 at 0:37

3 Answers 3

\documentclass[tikz, border=1cm]{standalone}
\usetikzlibrary{tikzmark, fit}
\begin{tikzpicture}[remember picture]
\node {abc, \subnode{sub}{\textcolor{green}{def}} ,};
\node[fit=(sub), draw, inner sep=0pt, red] {};

Text partly colored and framed


This version uses a savebox.

\documentclass{standalone}% so I don't have to crop it

\bgroup% use local registers
  \node[draw=red, text=blue] (B) {def};
\node at (0,0) (A) {abc, \usebox0,};



For a simple rectangle, the \fbox is enough.

In this example, I'm ignoring inner ysep and assume it has the same value as inner xsep.


\documentclass[tikz, border=1cm]{standalone}
    \pgfmathsetlength\fboxsep{\pgfkeysvalueof{/pgf/inner xsep}-.5\pgflinewidth}%


enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .