3

I am trying to highlight some parts of a document by setting them inside boxes drawn with TikZ. In order to retain a readable document, I do so with a simple macro, \focus:

\documentclass{article}
\usepackage{tikz}
\begin{document}

% highlighting
\newcommand*{\focus}[1]{%
\tikz[baseline]\node[rectangle, inner ysep=0pt, inner xsep=2pt, anchor=text, fill=lightgray, anchor=base]{$#1$};%
}

\focus{x} \focus{g}
\end{document}

As you can see, the highlighting works in general, but the size of the drawn rectangle is determined by the size of the enclosed characters. Is there any way to obtain a uniform size for a whole line?

choeger
  • 915
  • Add a strut: \newcommand*{\focus}[1]{% \tikz[baseline]\node[rectangle, inner ysep=0pt, inner xsep=2pt, anchor=text, fill=lightgray, anchor=base]{\strut$#1$};% }. Related/duplicate: http://tex.stackexchange.com/questions/133227/how-to-align-text-in-tikz-nodes-by-baseline and http://tex.stackexchange.com/questions/301432/align-tikz-word-overlays – Steven B. Segletes Oct 31 '16 at 15:16

2 Answers2

3

I'd use a phantom (and a positive y sep):

\documentclass{article}
\usepackage{tikz}
\begin{document}

% highlighting
\newcommand*{\focus}[1]{%
  \tikz[baseline]
    \node[
      rectangle,
      inner ysep=1pt,
      inner xsep=2pt,
      anchor=text,
      fill=lightgray,
      anchor=base
    ]{$\vphantom{ly}#1$}
  ;%
}

x\focus{x} \focus{g}x
\end{document}

enter image description here

egreg
  • 1,121,712
1

Another option using tcbox from tcolorbox instead of TikZ.

\documentclass{article}
\usepackage[most]{tcolorbox}

\newtcbox{\focus}[1][gray]{enhanced, 
    on line, 
    size=tight, 
    boxsep=1pt,
    sharp corners, 
    frame hidden,
    before upper=\vphantom{ly},     
    colback=#1}

\begin{document}
x\focus{x} \focus{g}x \focus[red]{h}
\end{document}

enter image description here

Ignasi
  • 136,588