[Tex/LaTex] Tabularx with different multicolumn spans

multicolumntabularx

\documentclass{article}

%\usepackage[margin=1in]{geometry}
\usepackage{multirow,tabularx}
\newcolumntype{Y}{>{\centering}X}

\begin{document}

\begin{table}
    \begin{tabularx}{\textwidth}{
        *{4}{|m{\dimexpr.25\linewidth-2\tabcolsep}} |   
    }
\hline
1 & 2 & 3 & 4 \\ \hline
\multicolumn{3}{|Y|}{1-3 centered} & 4 \\ \hline
\multicolumn{2}{|Y|}{1-2 centered} & \multicolumn{2}{Y|}{3-4 centered} \\ \hline
    \end{tabularx}
\end{table}
\end{document}

result

Why is the first cell from the second row (multicol 3) NOT centering across the 3 columns, but instead only over 2 colums as the next row does?

Best Answer

There no need to use tabularx only to define a strange \newcolumntype{Y}{>{\centering}X} only used in multicolumns, when you have already defined your columns in order to occupy all the line width: *{4}{|m{\dimexpr.25\linewidth-2\tabcolsep}} |.

A simple tabular with c multicolumns does the trick.

I have also added a -1.25\arrayrulewidth to avoid overfull hbox. The value 1.25\arrayrulewidth is due to 1\arrayrulewidth plus .25\arrayrulewidth, the latter is 1\arrayrulewidth (the width of the 5th rule) divided by 4 (the number of columns). Thanks to Zarko for having pointed out the need of the .25.

\documentclass{article}
\usepackage{array}

\begin{document}

    \begin{table}
        \begin{tabular}{
                *{4}{|m{\dimexpr.25\linewidth-2\tabcolsep-1.25\arrayrulewidth}} |   
                }
            \hline
            1 & 2 & 3 & 4 \\ 
            \hline
            \multicolumn{3}{|c|}{1-3 centered} & 4 \\ \hline
            \multicolumn{2}{|c|}{1-2 centered} & \multicolumn{2}{c|}{3-4 centered} \\ 
            \hline
        \end{tabular}
    \end{table}
\end{document}

enter image description here

Related Question