# Align TikZ Word Overlays

I am using TikZ to produce 'highlights' over individual words as follows:

\newcommand*\hl[1]{\tikz[overlay]\node[draw, fill={rgb:black,1;red,5},
inner sep=1mm, anchor=text, rectangle, rounded corners=1mm,
minimum height=8mm] {#1};\phantom{#1}}

\hl{Word} \hl{one}, \hl{another} \hl{long} \hl{phrase}.


As you can see, although the sentence is aligned, the highlights themselves are not. How can I fix this?

-

Add a \strut to each \hl.

\documentclass[12pt]{article}

\usepackage{tikz}
\newcommand*\hl[1]{\tikz[overlay]\node[draw, fill={rgb:black,1;red,5},
inner sep=1mm, anchor=text, rectangle, rounded corners=1mm,
minimum height=8mm] {#1\strut};\phantom{#1}}
\begin{document}

\Huge \hl{Word} \hl{one}, \hl{another} \hl{long} \hl{phrase}.
\end{document}


You might be able to tighten it up a bit by reducing the inner sep value, or else with a custom strut, such as

\def\mystrut{\rule[-.5\dp\strutbox]{0pt}{.75\dimexpr\ht\strutbox+\dp\strutbox}}


and then use \mystrut in the \hl definition.

-

You could add text depth to also account for this possible length. To avoid the overlapping I suggest also adding inner xsep and specify a suitable value there to avoid overlapping of the boxes.

\documentclass[border=3mm]{standalone}
\usepackage{tikz}
\newcommand*\hl[1]{%
\tikz[overlay]%
\node [
draw,
fill={rgb:black,1;red,5},
inner sep=1mm,
anchor=text,
rectangle,
rounded corners=1mm,
%                minimum height=8mm,
text height=2ex,
] {#1}
;%
\phantom{#1}%
}
\begin{document}
\hl{Word} \hl{one}, \hl{another} \hl{long} \hl{phrase}.
\end{document}


-

Add a \vphantom{gh} to your \hl macro. That is because you have different kinds of letters; some with more depth down the baseline and others with more height. So, we choose one from each group to have the same text height in all cases. Also, 8mm is an absolute measure which may not suit certain font sizes, so, some fontsize dependent measure like minimum height=1em would be better.

\documentclass[12pt]{article}
\usepackage{tikz}
\newcommand*\hl[1]{\tikz[overlay]\node[draw, fill={rgb:black,1;red,5},
inner sep=1pt, anchor=text, rectangle, rounded corners=1mm,
minimum height=1em] {#1\vphantom{gh}};\phantom{#1}}
\begin{document}

\hl{Word} \hl{one}, \hl{another} \hl{long} \hl{phrase}.

\end{document}


-

Just another solution with tcolorbox instead of TikZ.

on line option aligns all boxes to their baseline and doesn't create new paragraphs between them.

before upper=\strut assures same height for all boxes.

In this case size=small fixes all box margins and border width, but if necessary any particular margin can be fixed independently.

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

\newtcbox{hl}{size=small, colback=red!90!black,
on line, before upper=\strut}

\begin{document}
\hl{Word} \hl{one}, \hl{another} \hl{long} \hl{phrase}.
\end{document}


-