How to force one element to have the same width as another? (phantom?)

(Context: I have a case where I'm using MathJax and an HTML table with cells for various expressions that I want to align, so I can't use an align environment.)

Is there a way to force one element to have the same width as another? I know about \phantom, so for example these fragments should have the same width:

a+x^2+b

a+\phantom{x^2}+b


But what if I want to show a+0+b instead of a+x^2+b, and I want 0 to be centered in an hbox with the same width as x^2?

• note that most tex solutions are going to involve the measuring of a box but that won't work in mathjax, mathjax specific solutions are off-topic though as mathjax doen't use tex. – David Carlisle Jul 1 '17 at 20:11
• I would like to voice my continued disagreement with the mathjax-is-off-topic philosophy of this site. – Jason S Feb 1 '18 at 21:04
• if you comment there it just pings me, and the discussion about that was mostly before I was active on the site. You could raise it again on meta but I don't suppose the issues have really changed. see tex.meta.stackexchange.com/questions/3482/mathjax-boilerplate – David Carlisle Feb 1 '18 at 23:17

You can centre the 0 in a box the size of the omitted expression

\documentclass{article}

\begin{document}

$a+x^2+b$

$a+\phantom{x^2}+b$

\sbox0{$x^2$}

$a+\makebox[\wd0]{$0$}+b$

\end{document}

• thanks -- useful to me even if it doesn't work in MathJax. – Jason S Jul 1 '17 at 20:15
• MathJax doesn't support TeX Box arithmetic though – David Carlisle Jul 1 '17 at 20:15

Aha, the use of \rlap and \llap worked for me for left- and right-justified content:

a+\phantom{x^2}\llap{0}+b


I don't know how to get centered context but I can relax that requirement if I have to.

• I don't think you'll be able to easily get centered alignment this way. However, for the record, I think the 0 in this equation system looks best when it is right-aligned, and your answer would thus be the best to that end. – marsupilam Jul 1 '17 at 21:09

Of course this won't work in MathJax.

\documentclass{article}
\usepackage{mathtools,calc}

\begin{document}

$a+x^2+b$

$a+\phantom{x^2}+b$

$a+\mathmakebox[\widthof{$\displaystyle x^2$}]{0}+b$

\end{document}


A solution with the eqparbox package: it defines tagged box commands so a tagged box has the width of the widest contents in boxes sharing the same tag (requires two compilations):

\documentclass{article}
\usepackage{mathtools,calc}
\usepackage{eqparbox}
\newcommand\eqmathbox[2][]{\eqmakebox[1]{$#2$}}

\begin{document}

$a+\eqmathbox[M]{x^2}+b$

$a+\eqmathbox[M]{0}+b$

\end{document}