[Tex/LaTex] How to draw tikz node behind text

annotationsbackgroundsbeamertikz-pgf

I am trying to annotate an equation using tikz. I'd like to highlight a part of that equation using a tikz node, but the left part of the equation gets covered:

\documentclass[varwidth, border={0pt 4pt 0pt 4pt}]{standalone}
\usepackage{tikz}
\begin{document}
  $y(x) = g(x)f(x)h(x)$

  \bigskip
  $y(x) = g(x)
  \tikz[remember picture, overlay]{
      \node[fill=gray!20, inner sep=4pt, anchor=text, rectangle, rounded corners=1mm]{$f(x)$};
  }
  \phantom{f(x)}
  h(x)$
\end{document}

The first part of the equation, g(x), gets covered by the node, while the right hand side, h(x), doesn't, because it appears after the node in the LaTeX code:

test using tikz node

Instead, I would like to have the node in the background, behind the rest of the equation, while preserving the original spacing within the equation:

desired result

Best Answer

TikZ may be an overkill for such simple tasks, you can try tcolorbox, mdframed, fancybox, etc. If you still like TikZ, your example can be easily modified.

\documentclass[12pt,a4paper]{book}
\usepackage{tikz,amsmath}
\usepackage{graphicx}
\begin{document}

\begin{equation*}
  y(x) = g(x)\,
  \tikz[remember picture, overlay]{
    \node[fill=gray!20, inner sep=1pt, anchor=text, rectangle, rounded corners=1mm]{$f(x)$};
  }
  \phantom{f(x)}\,
  h(x)
\end{equation*}

\end{document}

enter image description here