[Tex/LaTex] Using multiple styles inside a TikZ node label

tikz-pgftikz-styles

I would like to do something like:

enter image description here

using PGF styles in TikZ

Here is the code:

\documentclass[tikz,convert={outfile=mwe.png}]{standalone}
\begin{document}
\pgfkeys{%
  /tikz/style A/.style = {text=blue},
  /tikz/style B/.style = {text=red},
}

\begin{tikzpicture}
  \node [thin, draw, style A] at (1,3) {Style A};
  \node [thin, draw, style B] at (1,2) {Style B};
  \node [thin, draw] at (1,1) {Style A + Style B};
\end{tikzpicture}
\end{document}

But the "Style A + Style B" is always the same color. How can I do to get "Style A" in style A and "Style B" in style b and the "+" in the node style?

Of course I could use something like {\color{blue}Style A} + {\color{red}Style B} but it's not very flexible. I prefer to use styles instead.

Thanks in advance.

Best Answer

If you want this to work for any text then I can see two options which allow you to keep the flexability in that you only need to change the color once.

The first method uses \colorlet to define the colors to use and then applies the solution you proposed via \textcolor.

\colorlet{StyleAColor}{blue}
\colorlet{StyleBColor}{red}

\tikzset{
    style A/.style={text=StyleAColor},
    style B/.style={text=StyleBColor},
}

\node [thin, draw] at (1,1) {\textcolor{StyleAColor}{Style A} + \textcolor{StyleBColor}{Style B}};

The second option involves nesting tikzpictures and this is not recommended:

\node [thin, draw] at (1,0) {
    {\tikz[baseline=0pt] \node[style A, Inner Style] {Style A};} 
    {\tikz[baseline=0pt] \node[Inner Style] {+};}
    {\tikz[baseline=0pt] \node[style B, Inner Style] {Style B};}

enter image description here

Code:

\documentclass[border=2pt]{standalone}

\usepackage{tikz}
\usepackage{xcolor}

\colorlet{StyleAColor}{blue}
\colorlet{StyleBColor}{red}

\tikzset{
    Inner Style/.style={inner sep=0pt, outer sep=0pt},
    style A/.style={text=StyleAColor},
    style B/.style={text=StyleBColor},
}


\begin{document}
\begin{tikzpicture}
  \node [thin, draw, style A] at (1,3) {Style A};
  \node [thin, draw, style B] at (1,2) {Style B};
  \node [thin, draw] at (1,1) {\textcolor{StyleAColor}{Style A} + \textcolor{StyleBColor}{Style B}};
  \node [thin, draw] at (1,0) {
      {\tikz[baseline=0pt] \node[style A, Inner Style] {Style A};} 
      {\tikz[baseline=0pt] \node[Inner Style] {+};}
      {\tikz[baseline=0pt] \node[style B, Inner Style] {Style B};}
  };
\end{tikzpicture}
\end{document}