# How to make text appear in the middle of a phantom in math mode?

I want to make a part of an equation to appear in the center of a (horizontal) phantom. This would be awesome for example for making bra-kets that are all of the same width and still look natural. This is what I want the result to look like:

.

I know how to write right- and left-aligned text inside a phantom:

\usepackage{mathtools}
\begin{gather*}
1 + \mathrlap{B}\phantom{ABC} + 2 \\
1 + \phantom{ABC}\mathllap{B} + 2 \\
1 + ABC + 2
\end{gather*}


I've tried this macro to make a centered text, but it didn't work:

\usepackage{mathtools}
\usepackage{calc}

\parbox{\widthof{#1}/2}{}
\mathclap{#2}
\parbox{\widthof{#1}/2}{}
}


• I'm not sure but I think that \mathclap should be in math mode. Jun 8, 2020 at 16:16
• Yes, \mathclap definitely works in math mode, but it makes a zero-width box with its contents centered on the box. But actually positioning the box to the center of the phantom – that's the hard part.
– m93a
Jun 8, 2020 at 16:23
• You know this, but another alternative is to align at the operators. Jun 8, 2020 at 22:29

You don't really need to use \mathclap, you can just place what you want to center in a box of the appropriate width.

\documentclass{article}
\usepackage{amsmath}
\usepackage{calc}
\mathord{\makebox[\widthof{$$#1$$}]{$$#2$$}}%
}
\begin{document}
\begin{gather*}
1 + \mask{ABC}{B} + 2 \\
1 + ABC + 2
\end{gather*}
\end{document}


A version that works in all styles.

\documentclass{article}
\usepackage{amsmath}

\makeatletter
\settowidth{\dimen@}{$\m@th#1#2$}%
\makebox[\dimen@]{$\m@th#1#3$}%
}
\makeatother

\begin{document}

\begin{gather*}
1 + \mask{ABC}{B} + 2 \\
1 + ABC + 2 \\
1 + \mask{\int_0^1 f(x)\,dx}{y}+2 \\
1 + \int_0^1 f(x)\,dx+2
\end{gather*}

$\begin{array}{c} 1 + \mask{\int_0^1 f(x)\,dx}{y}+2 \\ 1 + \int_0^1 f(x)\,dx+2 \end{array}$

$\sum_{\substack{1\le \mask{w}{i}\le n \\ 1\le w\le n}} a_{iw}$

\end{document}