5

I have a table with two columns of different widths. I want to place my table in my page such that the line between the two columns falls on the center of the page.

If the columns were the same size then it would be trivial, but they aren't.

2

You can measure the column widths (two consecutive compilations might be needed), put the entire table in a savebox for the calculation and use it after a respective shifting.

Note: I've added a 0.5\textwidth long rule for demonstration.

enter image description here

\documentclass{article}

\usepackage{environ}

\makeatletter
\NewEnviron{mtabular}[3][c]{%
  \begingroup
  \renewcommand{\multicolumn}[3]{\multispan{##1}##3}%
  \let\\\cr
  \setbox\tw@=\vbox{
    \ialign{&##\unskip\hfil\cr\BODY\crcr}%
    \get@widths{#3}%
  }%
  \endgroup
  \begin{tabular}[#1]{#2}\BODY\end{tabular}}

\def\get@widths#1{%
  \def\@temp{\else\@latex@warning{No such column}\fi}
  \setbox\z@=\lastbox
  \get@next@width
  \xdef#1##1{%
    \noexpand\ifcase##1\relax\unexpanded\expandafter{\@temp}%
  }%
}
\def\get@next@width{%
  \setbox\z@=\hbox{\unhbox\z@\unskip\global\setbox\@ne=\lastbox}%
  \ifvoid\@ne
  \else
    \edef\@temp{\noexpand\or\the\wd\@ne\unexpanded\expandafter{\@temp}}%
    \expandafter\get@next@width
  \fi
}
\makeatother

\newsavebox{\mybox}

\begin{document}

\noindent\rule{0.5\textwidth}{1pt} % demo only

\begin{lrbox}{\mybox}%
\begin{mtabular}{|l|c|r|}{\foo}%
alma bagoly & alma & bagoly \\\hline
BAGOLY & \multicolumn{2}{|c|}{alma bagoly alma} \\\hline
bagoly & bagoly & bagoly
\end{mtabular}%
\end{lrbox}

\noindent%
\hspace*{0.5\textwidth}%
\hspace*{-\foo{1}}%
\hspace*{-2\tabcolsep}%
\usebox{\mybox}

\end{document}

Shifting explanation: to the middle, back by the first column content width, back by 2 column separation lengths.

Related on measuring column width: Measure the column width of a table

0

I'm not sure how to get tabular to do this, but it's not too hard with a plain TeX halign.

$$\vbox{\halign{\hbox to 1in{\hss #}\ &\ \hbox to 1in{#\hss}\cr
Items on the left&Something on the right\cr
More on the left&With very long lines on the right too.\cr
}}$$

The idea is to make an alignment with two boxes of fixed width and then use \hss to ignore the width on the left and right respectively. \hss produces glue that stretches or shrinks as needed. You can make the boxes any reasonable width, since we are ignoring the width of the contents. Providing they are the same width the gutter will be in the middle. You could adjust the width of the boxes if you wanted to split the columns in a different proportion.

Once we have the halign we wrap it in a vbox and then in a math display to get it nicely centered on the page.

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.