我有一张方格表(https://tex.stackexchange.com/a/49751/112272)。我想给单元格着色。我该怎么做?我使用了 colortbl 包,但是不起作用。
\documentclass{article}
\usepackage{array}
\usepackage{calc}
\usepackage{xcolor}
\usepackage{colortbl}
\newlength\celldim
\newlength\fontheight
\newlength\extraheight
\newcounter{sqcolumns}
\newcolumntype{S}{
@{}
>{\centering \rule[-0.5\extraheight]{0pt}{\fontheight + \extraheight}%
\begin{minipage}{\celldim}\centering}
p{\celldim}
<{\end{minipage}}
@{} }
\newcolumntype{Z}{ @{} >{\centering} p{\celldim} @{} }
\newenvironment{squarecells}[1]
{\setlength\celldim{4.5em}%
\settoheight\fontheight{A}%
\setlength\extraheight{\celldim - \fontheight}%
\setcounter{sqcolumns}{#1 - 1}%
\begin{tabular}{|S|*{\value{sqcolumns}}{Z|}}\hline}
% squarecells tabular goes here
{\end{tabular}}
\newcommand\nl{\tabularnewline\hline}
\begin{document}
\Huge
\begin{squarecells}{4}
This is a long line & 3 & 2 & 13 \nl
\cellcolor{red}5 & 10 & 11 & 8 \nl
9 & 6 & 7 & 12 \nl
4 & 15 & 14 & 1 \nl
\end{squarecells}
\end{document}
谢谢
答案1
您在这里使用的表格有点不规范。由于您尝试将宽度设置为\celldim
,因此您应该考虑到默认情况下,每列之间都有一些额外的间距,这些间距由长度控制\tabcolsep
。因此,您的列实际上会像一样宽\celldim+\tabcolsep
,但您的minipage
宽度只有\celldim
-。
将此添加到您的示例中意味着改变\tabcolsep
您的内心environment
\newenvironment{squarecells}[1]
{\setlength\celldim{4.5em}%
\settoheight\fontheight{A}%
\setlength\tabcolsep{0pt}
\setlength\extraheight{\celldim - \fontheight}%
\setcounter{sqcolumns}{#1 - 1}%
\begin{tabular}{|S|*{\value{sqcolumns}}{Z|}}\hline}
% squarecells tabular goes here
{\end{tabular}}
为了说明什么\tabcolsep
,这里有一个简单的例子。
输出
代码
\documentclass{article}
\usepackage{caption}
\begin{document}
\begin{table}[hbt]
\centering
\caption{\texttt{\textbackslash tabcolsep} unchanged }
\begin{tabular}{*{3}{|l}|}
\hline
Some & random & stuff\\
foo & bar & baz\\
\hline
\end{tabular}
\end{table}
\begin{table}[hbt]
\setlength{\tabcolsep}{0pt}
\centering
\caption{\texttt{\textbackslash tabcolsep} set to 0 }
\begin{tabular}{*{3}{|l}|}
\hline
Some & random & stuff\\
foo & bar & baz\\
\hline
\end{tabular}
\end{table}
\end{document}