How to have a background which exactly fits the text height/depth?

TeX does know the glyph bounding boxes as they are reported by the font. Usually, these bounding boxes are not exact:

  • Side bearings are added (left and right space).
  • Curvy elements tend to stick a little outside.
  • Sometimes the glyph is outside the bounding box by design, example: \not.

The example of the question uses font cmr17.pfb. A font editor like fontforge reveals the real dimensions of the glyphs:

  • Left side bearing of S: 46
  • Height of S: 699
  • Depth of p: -195
  • Right side bearing of p: 33

The font uses 1000 units for 1 em. However, 1em by TeX is a little smaller. The right value is the nominal value 24.88pt of the font: OT1/cmr/m/n/24.88 (result of \the\font).

Combined:

\documentclass[tikz]{standalone}

\newsavebox\StopBox
\sbox\StopBox{%
  \Huge
  \wlog{Font: \the\font}% Font: \OT1/cmr/m/n/24.88
  \dimen0=24.88pt
  \kern-.046\dimen0\relax % cancel left side bearing of S/cmr17
  \smash{Stop}% no height, no depth
  \kern-.033\dimen0\relax % cancel right side bearing of p/cmr17
  \vrule
    width 0pt
    height .699\dimen0 % height of S
    depth .195\dimen0 % depth of p
  \relax
}
\begin{document}
\begin{tikzpicture}
  \node[draw=gray, very thick, font=\Huge] (stop) {%
    \setlength{\fboxsep}{0pt}%
    \colorbox{lightgray}{\usebox\StopBox}%
  };
\end{tikzpicture}
\end{document}

Result


TeX has no information about the exact content of each glyph. TeX knows only the bounding boxes provided by the font (via the .tfm file).

As David Carlisle says in his comment, if the font designer chooses to make the character stray out of that area than there is no way to tell.