3

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.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}
\node at (0,0) (A) {abc,};
\node[draw,color=red,right = 1ex of A] (B) {\textcolor{blue}{def}};
\node[right = 1ex of B] (C) {,};
\end{tikzpicture}
\end{document}

My output: enter image description here

4
  • 1
    Try anchor=base or similar things.
    – Symbol 1
    Commented 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
    Commented 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. Commented Oct 23, 2022 at 0:30
  • base right=of … could help with @Symbol1's tip. Commented Oct 23, 2022 at 0:37

3 Answers 3

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

Text partly colored and framed

3

This version uses a savebox.

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

\begin{document}
\bgroup% use local registers
\sbox0{\begin{tikzpicture}[baseline=(B.base)]
  \node[draw=red, text=blue] (B) {def};
\end{tikzpicture}}%
\begin{tikzpicture}
\node at (0,0) (A) {abc, \usebox0,};
\end{tikzpicture}
\egroup
\end{document}

demo

0

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.

Code

\documentclass[tikz, border=1cm]{standalone}
\DeclareDocumentCommand{\node}{O{.}O{.}m}{%
  \vphantom{#3}\smash{%
    \setlength\fboxrule{\pgflinewidth}%
    \pgfmathsetlength\fboxsep{\pgfkeysvalueof{/pgf/inner xsep}-.5\pgflinewidth}%
    \textcolor{#1}{\fbox{\textcolor{#2}{#3}}}%
  }%
}
\begin{document}
\tikz\node{abc,\node[red][green]{def},};
\end{document}

Output

enter image description here

You must log in to answer this question.

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