[Tex/LaTex] Drawing boxes around words

boxes

I want to put some small boxes around certain words in a paragraph. The boxes will never contain more than one word.

The \ovalbox command described in the fancybox documentation is close to what I need. However, I found some problems:

  • The rounded corners do not line up with the sides perfectly.
  • Text to the left and right in the paragraph are pushed away.
  • The spacing between lines in the paragraph is increased vertically.

I would like to create boxes which:

  • Adjust horizontally to fit the width of the text inside.
  • Have rounded or beveled corners.
  • Can be filled with a solid color.
  • Will not cause any text inside or around the box to move.
  • Will not impact the vertical spacing of lines.

Best Answer

You can use TikZ with the overlay option and a correct anchor. That would look like this:

\documentclass{article}
\usepackage{tikz}
\newcommand\mybox[2][]{\tikz[overlay]\node[fill=blue!20,inner sep=2pt, anchor=text, rectangle, rounded corners=1mm,#1] {#2};\phantom{#2}}
\begin{document}
   \noindent
   this is some text \mybox[fill=blue!20]{box} text\\
   this is some text box text
\end{document}

You can specify extra options (like I have done here for the color). By using the overlay option and the text anchor we ensure correct placement and no influence on spacing. The phantom is added to get the normal spacing for the content of the box. This is the result of the example code:

TikZ text box

Edit: To show that the vertical spacing is not affected either, consider the following:

\documentclass{article}
\usepackage{tikz}
\newcommand\mybox[2][]{\tikz[overlay]\node[fill=blue!20,inner sep=2pt, anchor=text, rectangle, rounded corners=1mm,#1] {#2};\phantom{#2}}
\begin{document}
  \begin{minipage}{0.4\textwidth}
    \noindent
    this is some text \mybox[fill=blue!20]{box} text\\
    this is some text box text
  \end{minipage}
  \begin{minipage}{0.4\textwidth}
    \noindent
    this is some text box text\\
    this is some text box text
  \end{minipage}    
\end{document}

Which results in:

TikZ text box vertical spacing