7

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:

enter image description here

.

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}

\newcommand{\hmask}[2]{
    \parbox{\widthof{#1}/2}{}
    \mathclap{#2}
    \parbox{\widthof{#1}/2}{}
}

\newcommand{\mask}[2]{\vphantom{#1}\hmask{#1}{#2}}
3
  • I'm not sure but I think that \mathclap should be in math mode.
    – Sigur
    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.
    – Davislor
    Jun 8, 2020 at 22:29

2 Answers 2

17

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}
\newcommand*{\mask}[2]{%
    \mathord{\makebox[\widthof{\(#1\)}]{\(#2\)}}%
}
\begin{document}
\begin{gather*}
    1 + \mask{ABC}{B} + 2 \\
    1 + ABC + 2
\end{gather*}
\end{document}

12

A version that works in all styles.

\documentclass{article}
\usepackage{amsmath}

\makeatletter
\newcommand{\mask}[2]{{\mathpalette\mask@{{#1}{#2}}}}
\newcommand{\mask@}[2]{\mask@@{#1}#2}
\newcommand{\mask@@}[3]{%
  \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}

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.