[Tex/LaTex] Attractive Boxed Equations

boxesequationsframed

I often used \boxed{...} from the AMS math package to place a box around important equations. However, this approach often produces somewhat awkward looking output. Consider

\documentclass{article}
\pagestyle{empty}
\usepackage{amsmath}
\begin{document}
 \[
 \boxed{c_i = \sum_jA_{ij}}
 \]
 \[
 \boxed{c_i = \langle\psi|\phi\rangle}
 \]
\end{document}

enter image description here

Observe that in the first case the box looks unbalanced while in the second case could do with more padding on both the top and bottom. What is the best way to go about this? I know that I could use a \phantom but am wondering if more elegant solutions exist.

Best Answer

You can use the empheq package and then define your own boxing command. It can be a standard Latex \fbox or a Tikz box, or any other type of box. Look at the example below. I have defined a color box (to make it more interesting) with two optional arguments for padding the space above and below the equation

\mybluebox[<top pad>][<bot pad>]{<contents>}

The keyval package is already loaded so you can make a fancy keyval interface, but I leave that as an exercise to the reader ;-)

\documentclass{article}

\usepackage{color}
\definecolor{myblue}{rgb}{.8, .8, 1}

\usepackage{amsmath}
\usepackage{empheq}

\newlength\mytemplen
\newsavebox\mytempbox

\makeatletter
\newcommand\mybluebox{%
    \@ifnextchar[%]
       {\@mybluebox}%
       {\@mybluebox[0pt]}}

\def\@mybluebox[#1]{%
    \@ifnextchar[%]
       {\@@mybluebox[#1]}%
       {\@@mybluebox[#1][0pt]}}

\def\@@mybluebox[#1][#2]#3{
    \sbox\mytempbox{#3}%
    \mytemplen\ht\mytempbox
    \advance\mytemplen #1\relax
    \ht\mytempbox\mytemplen
    \mytemplen\dp\mytempbox
    \advance\mytemplen #2\relax
    \dp\mytempbox\mytemplen
    \colorbox{myblue}{\hspace{1em}\usebox{\mytempbox}\hspace{1em}}}

\makeatother

\begin{document}
\begin{empheq}[box={\mybluebox[5pt]}]{equation*}
    c_i = \sum_j A_{ij}
\end{empheq}

\begin{empheq}[box={\mybluebox[2pt][2pt]}]{equation*}
    c_i = \langle\psi|\phi\rangle
\end{empheq}
\end{document}

enter image description here