简体   繁体   中英

How to redefine column width in Latex?

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.

在此处输入图像描述

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.

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}

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM