# horizontal centering within \valign cells

I'm trying to use \valign to make an array of items. (See my self-answer to another question.) I'm doing this because I want to specify the items per column instead of per row, and because I want control over the spacing. I'm using LaTeX but these are macros.

I'm happy with the following, except that the items are not vertically centred within their column, so this question is about how to achieve that.

\documentclass{article}
\usepackage{amsmath}

% this can't be an environment because the code for \end can't have parameters.
\newcommand{\colarray}[3]{
\vcenter{\hbox{\valign{&\vfil\vbox{\parindent=0pt\tabskip=#2\hsize=#1##}\vfil\cr%
#3%
}}\vskip-#2}%
}

\newcommand*\col[1]{#1\cr}

\begin{document}

$$x = \colarray{4mm}{2mm}{ \col{1 & 2 & 3} \col{4 & 5 & \Big(6\Big)} }$$

\end{document}


This produces

From my current rather hazy understanding, centering the items should involve putting each one in an \hbox and using \vfil. However, if I try that the results are not as expected:

\documentclass{article}
\usepackage{amsmath}

% this can't be an environment because the code for \end can't have parameters.
\newcommand{\colarray}[3]{
\vcenter{\hbox{\valign{&\vfil\vbox{\parindent=0pt\tabskip=#2\hsize=#1\hbox to #1{\hfil##\hfil}}\vfil\cr%
#3%
}}\vskip-#2}%
}

\newcommand*\col[1]{#1\cr}

\begin{document}

$$x = \colarray{4mm}{2mm}{ \col{1 & 2 & 3} \col{4 & 5 & \Big(6\Big)} }$$

\end{document}


Here's the result:

As you can see the '3' is horizontally aligned differently from the '1' and '2', and the '(6)' is not horizontally centred with respect to the '4' and '5'.

I am not able to work out why this is, so my questions are (1) why is this happening, and (2) how can I fix it?

• When you use \valign, you give up the common baseline that \halign would give you. To compensate for that, you can make all vboxes in your alignment the same height and insert a "strut" to control the baseline. See this answer for an example. Aug 10, 2022 at 13:00

## 2 Answers

You need to remove the spaces before each & in your usage of \colarray, as they are significant when they get substituted in the inner \hbox. Alternatively, replace ## with $##$ in the definition of \colarray. Also, I don't think 4mm is big enough for the parenthesized "6"; to align the columns, you will need to increase it.

By the way, you do not need to set \parindent and \hsize in your second attempted solution.

This is similar to RobertR's suggestions, but as a full example.

\documentclass{article}
\usepackage{amsmath}

% this can't be an environment because the code for \end can't have parameters.
% ?? It would be more natural as an environment with \\ like array
\newcommand{\colarray}[3]{%
\vcenter{\hbox{\valign{&\vfil\tabskip=#2\hbox to #1{\strut\hfil$##$\hfil}\vfil\cr%
#3%
}}\vskip-#2}}

\newcommand*\col[1]{#1\cr}

\begin{document}

$$x = \colarray{5mm}{2mm}{ \col{1 & 2 & 3} \col{4 & 5 & \Bigl(6\Bigr)} }$$

\end{document}