I have a general question. I would like to center tables on the page, when I do not know the width. What is more, I am using tabularx
and sometimes the width specified may be too small, meaning that the table is wider than the first argument to tabularx.
Here is some context for my question. I develop an R package which prints out tables in HTML, LaTeX etc. So, users may set the width - perhaps to a value which is too small for the content.
At the moment, a centered table uses \centering
, like this (simplified version):
\begin{table}[h]
\centering
\begin{threeparttable}
\begin{tabularx}{0.5\textwidth}{p{0.5\textwidth}}
\multicolumn{1}{l}{Some content here} \tabularnewline[-0.5pt]
\end{tabularx}\end{threeparttable}
\end{table}
But that can lead to tables not being truly centered. Here's an example where the user has specified a too small table width for a wide table. As a result the table is not centered:
\documentclass{article}
\usepackage{threeparttable}
\usepackage{tabularx}
\usepackage{multirow}
\begin{document}
\begin{table}[h]
\centering
\begin{threeparttable}
\begin{tabularx}{0.2\textwidth}{p{0.2\textwidth}}
\multicolumn{1}{l}{Some very long content that goes on and on and on} \tabularnewline[-0.5pt]
\end{tabularx}\end{threeparttable}
\end{table}
\end{document}
Is there a way to make sure that tables stay centered?
Note that the multicolumn command overrides the table width specification. I know about this, and it is probably not optimal. But by default, my cells aren't wrapped. If a user wants they can turn wrapping on, in which case the multicolumn command would have a width spec of p{0.2\textwidth}
or whatever. The point is, sometimes users may do things that make tables wider than tabularx thinks they are; is there a way to ensure that nevertheless, they are truly centered?
(Note 2: yes, I also know that in this case, multicolumn
is not doing anything. But sometimes there are genuine multicolumn cells; the command allows per-cell left/right/top/bottom-alignment; and writing TeX programmatically from a different language is hard.)
\begin{tabularx}{0.5\textwidth}{p(0.5\textwidth}}
makes very little sense:tabularx
is only useful if you specify at least anX
column.p
column specification (since no cell in the table uses it.)tabularx
. However, note that withtabular
and even withtabulary
that nonsense cell is not a problem to center the final fattened width of the table.