[Tex/LaTex] A \boxed alternative with nicer spacing

boxesmath-modespacing

I like using \boxed to emphasize my answers in homework problem sets. However, whenever I use superscripts/exponents inside the box, the box becomes taller than it seems it should. This causes two problems: the box looks bad, and it pushes other lines of text around.

Here's an example. Notice that the line spacing doesn't get changed until I use an exponent inside a box.

enter image description here

Is there an alternative to \boxed that won't have this problem? Or some other good way to solve this issue?

Best Answer

You can use tikzmark as from this answer by Andrew Stacey to mark the endpoints where you want the box. The \MyBox macro as defined below accepts an optional first parameter which allows you to get fancy boxes.

enter image description here

Notes:

  • This does require two runs: the first to compute the positions of the box, and the second to draw it in the correct spot.

Known Issues:

  • This won't work if the text crosses line boundaries. If this is an issue and you are willing to consider highlighting instead of a box you should refer to Cool Text Highlighting in LaTeX.

  • This version will not adjust properly for text that adjusts the vertical spacing (ex. \dfrac{1}{2} from the amsmath package). However, an updated version of this that adjusts to the correct height is provided at A \boxed alternative with minimal spacing?

Code:

\documentclass[border=5pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc,shapes}

\newcommand{\tikzmark}[1]{\tikz[overlay,remember picture] \node (#1) {};}
\newcommand{\DrawBox}[1][red]{%
    \tikz[overlay,remember picture]{
    \draw[#1]
      ($(bl)+(-0.2em,0.9em)$) rectangle
      ($(br)+(0.2em,-0.3em)$);}
}
\newcommand{\MyBox}[2][red]{\tikzmark{bl}#2\tikzmark{br}\DrawBox[#1]}

\begin{document}
    Lorem ipsum dolor sit amet. \MyBox{Lorem ipsum} dolor sit amet. Lorem ipsum dolor sit amet. 
    Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.  Lorem 
    ipsum \MyBox[blue]{$3.29 \times 10^{29}$} dolor sit amet. Lorem ipsum dolor sit amet. Lorem 
    ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem 
    \MyBox[draw=red,fill=yellow!20,,opacity=0.3]{$3.29 \times 10^{29}$} ipsum dolor sit amet. 
    Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.
\end{document}