[Tex/LaTex] Tabular cells with exact same width and multicolumn

multicolumntablestabularxwidth

I tried to design a table with some very specific preferences:

  • The table should span across the whole width

  • Each cell can have a different alignment

  • Each cell has exactly the same width

  • Some cells are multicolumn cells, 2 combined cells should have exactly the same width as 2 single cells

Here is a small sample of what I've tried:

\documentclass[]{article}

\usepackage[a4paper, top=25mm, left=25mm, right=25mm, bottom=20mm, headsep=5mm, footskip=10mm, headheight=25mm]{geometry}

\usepackage{tabularx}

\begin{document}
\noindent
\begin{table}[h!]
    \begin{tabularx}{\textwidth}{|X|X|X|X|} \hline
        \multicolumn{3}{|l|}{3 cells left}  & \multicolumn{1}{|r|}{1 cell right} \\ \hline
        \multicolumn{1}{|r|}{1 cell right}  & \multicolumn{3}{|l|}{3 cells left} \\ \hline
        \multicolumn{1}{|r|}{1 cell right}  & \multicolumn{1}{|r|}{1 cell right} & \multicolumn{2}{|r|}{2 cells right} \\ \hline
        \multicolumn{1}{|r|}{1 cell right}  & \multicolumn{1}{|r|}{1 cell right} & \multicolumn{1}{|r|}{1 cell right}   & \multicolumn{1}{|r|}{1 cell right} \\ \hline 
    \end{tabularx}         
\end{table}

\end{document}

The first column in this example is significantly smaller than the others.
I really hope that somebody can help me.

Best Answer

Your problems stem from the fact that your table, defined with 4 X columns really has none. It suffices to re-define X column type so as to ensure right alignment, and you'll have both a table that looks like what you want, and a simpler code. I also suppressed redundant vertical lines in \multicolumns:

\documentclass[a4paper]{article}

\usepackage[top=25mm, hmargin=25mm, bottom=20mm, headsep=5mm, footskip=10mm, headheight=25mm]{geometry}%

\usepackage{tabularx}
\renewcommand{\tabularxcolumn}[1]{>{\raggedleft\arraybackslash}m{#1}}

\begin{document}

\begin{table}[!h]
    \begin{tabularx}{\linewidth}{|X|X|X|X|}
    \hline
        \multicolumn{3}{|l|}{3 cells left} & 1 cell right \\
         \hline
        1 cell right & \multicolumn{3}{l|}{3 cells left} \\
        \hline
        1 cell right & 1 cell right & \multicolumn{2}{r|}{2 cells right} \\
        \hline
        1 cell right & 1 cell right & 1 cell right & 1 cell right \\
        \hline
    \end{tabularx}
\end{table}

\end{document} 

enter image description here

Related Question