[Tex/LaTex] Highlight an equation within an align environment with color option

alignboxesequationshighlighting

I'd really like to do exactly what's being asked for in this question: Highlight an equation within an align environment, but with the ability to change the color when I call it, so that I could have one equation highlighted yellow, the next one highlighted lime, a third highlighted magenta, and a fourth highlighted yellow again, etc. (I'd also like the frame to be the same color as the highlight, but I'm pretty sure I can figure that part out. 🙂 ) I really like the first solution – the one with 15 votes – and would love to know how to tweak that one to do what I want – something like \alignedbox[yellow].

I'm not including a MWE since my question is just a follow-up to a previous one, but I can if it would be helpful.

I don't know if it's relevant or helpful, but what I'm doing right now is just using this that I found but don't really understand:

\newcommand{\highlight}[2][yellow]{\mathchoice%
    {\colorbox{#1}{$\displaystyle#2$}}% 
    {\colorbox{#1}{$\textstyle#2$}}%
    {\colorbox{#1}{$\scriptstyle#2$}}%
    {\colorbox{#1}{$\scriptscriptstyle#2$}}}%

and then using \phantom{} and \quad and such to try to get the horizontal spacing right so that things align the way I want. 🙂

Best Answer

You can just add one more parameter to the macro. Below I have made the first parameter to specify the color -- it is optional and defaults to yellow if not provided as in the first example:

enter image description here

Notes:

Code:

\documentclass{article}
\usepackage{calc}
\usepackage{amsmath}
\usepackage{xcolor}

\newlength\dlf
\newcommand\alignedbox[3][yellow]{
  % #1 = color (optional, defaults to yellow)
  % #2 = before alignment
  % #3 = after alignment
  &
  \begingroup
  \settowidth\dlf{$\displaystyle #2$}
  \addtolength\dlf{\fboxsep+\fboxrule}
  \hspace{-\dlf}
  \fcolorbox{red}{#1}{$\displaystyle #2 #3$}
  \endgroup
}

\begin{document}
\begin{align*}
    \alignedbox{a}{=b} &                        c  &= d \\
                c &= d & \alignedbox[magenta!20]{i}{=k} \\
                e &= f &                        g  &= h  
\end{align*}
\end{document}