[Tex/LaTex] Autofit a table to the column width

tablestwo-column

I am creating a two-column document using latex. I use the option \columnwidth to autofit a table to the column width, as shown in the following figure. The second column Value is too wide. How do I set equal width for two columns?


enter image description here


Here is my source code.

\begin{table}
    \centering
    \caption{Simulation parameters}
    \begin{tabular}{l|l}
        \hline
        Key                 & Value    \\
        \hline
        simulation duration & 12 hours \\
        update interval     & 1s       \\
        time-to-live        & 12 hours \\
        buffer size         & infinite \\
        message interval    & 20s      \\
        \hline
    \end{tabular}
\end{table}

\begin{table}
    \centering
    \caption{Simulation parameters}
    \begin{tabularx}{\columnwidth}{l|l}
        \hline
        Key                 & Value    \\
        \hline
        simulation duration & 12 hours \\
        update interval     & 1s       \\
        time-to-live        & 12 hours \\
        buffer size         & infinite \\
        message interval    & 20s      \\
        \hline
    \end{tabularx}
    \label{table: simulation parameters}
\end{table}

Best Answer

EDIT

@Mico pointed out a much better solution to this problem, as tabularx already comes with the column type X, which automatically does what you want:

\documentclass{article}

\usepackage{tabularx}

\begin{document}

\begin{table}
    \caption{Simulation parameters}
    \begin{tabularx}{\columnwidth}{X|X}
        \hline
        Key                 & Value    \\
        \hline
        simulation duration & 12 hours \\
        update interval     & 1s       \\
        time-to-live        & 12 hours \\
        buffer size         & infinite \\
        message interval    & 20s      \\
        \hline
    \end{tabularx}
    \label{table: simulation parameters}
\end{table}

\end{document}

As you already know the total width of your table, you can define the width of the columns as a fraction of \columnwidth

\documentclass{article}

\newlength\mylength
\setlength\mylength{\dimexpr.5\columnwidth-2\tabcolsep-0.5\arrayrulewidth\relax}

\begin{document}

\begin{table}
    %% \centering % not needed
    \caption{Simulation parameters}
    \begin{tabular}{p{\mylength}|p{\mylength}}
        \hline
        Key                 & Value    \\
        \hline
        simulation duration & 12 hours \\
        update interval     & 1s       \\
        time-to-live        & 12 hours \\
        buffer size         & infinite \\
        message interval    & 20s      \\
        \hline
    \end{tabular}
    \label{table: simulation parameters}
\end{table}

\end{document}

enter image description here

Related Question