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


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}
  $y(x) = g(x)f(x)h(x)$

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

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.


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


enter image description here