Search code examples
latextabularrenewcommand

How to define the actual column width in two-column Latex document (excluding the space between the columns)?


I would like to redefine \columnwidth and set it to the value corresponding to (\textwidth-\columnsep)/2. This is because I would like to use this redefined command inside tabular environment for controlling column width. The problem with \columnwidth is that it disregards the space between columns, therefore it doesn't do the job.

Here's what I'm talking about. The following code compiles but gives an undesirable output.

\documentclass[twocolumn]{article}
\usepackage{lipsum}
\setlength{\columnsep}{2cm}
\newcommand\testcolwidth{(\textwidth-\columnsep)/2}
\begin{document}
\lipsum
\begin{table}[!h]
\begin{tabular}{p{.25\columnwidth}|p{.75\columnwidth}}
\hline 
col 1 & col 2 
\end{tabular}
\end{table}
\lipsum
\end{document}

This is what the output look like. It's undesirable because I don't want this line (and the table) to stretch into the space between the columns.

enter image description here

I have tried to define column width with the following line:

\newcommand\testcolwidth{(\textwidth-\columnsep)/2}

It results in an error when using \testcolwidth in place of \columnwidth. The error reads: Illegal unit of measure (pt inserted)

Any help? Thanks a lot.


Solution

  • The columnwidth already takes into account the space between the columns of the article, what is missing in your code is the tabcolsep which defines the space between the table columns. In your example, this space gets added four times, once at the front, once at the end and once on each site of the |. If you want to manually define your table like this, you need to know in advance how many columns it will have:

    \documentclass[twocolumn]{article}
    \usepackage{lipsum}
    \setlength{\columnsep}{2cm}
    \newcommand\testcolwidth{\dimexpr\columnwidth-4\tabcolsep}
    \begin{document}
    \lipsum
    \begin{table}[!h]
    \begin{tabular}{p{.25\testcolwidth}|p{.75\testcolwidth}}
    \hline 
    col 1 & col 2 
    \end{tabular}
    \end{table}
    \lipsum
    \end{document}
    

    Much easier to let a package like tabularray do the job for you:

    \documentclass[twocolumn]{article}
    
    \usepackage{tabularray}
    \usepackage{lipsum}
    
    \begin{document}
    \lipsum[2]
    \begin{table}[!h]
    \begin{tblr}{
      colspec={X[1]|X[3]}
    }
    \hline
    col 1 & col 2 
    \end{tblr}
    \end{table}
    \lipsum[2]
    \end{document}
    

    enter image description here