# Color a squared Table

I have a squared Table (https://tex.stackexchange.com/a/49751/112272). I want to color the cells. How can I do that? I used the colortbl package, but this doesnt work.

\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}


Thank you

• what do you mean it doesn't work? I see a bright red cell, with a 5. Do you mean that the colorfill is somewhat wider than the cell itself? – Runar Aug 18 '16 at 12:15
• if that is the case, you could add \setlength{\tabcolsep}{0pt} inside the \newenvironment{squarecells} – Runar Aug 18 '16 at 12:25
• Yes the color doen't match the cell. Now I using \setlength{\tabcolsep}{0pt} and it works. Thank you. Can you explain the problem and what tabcolsep changes? (How can I mark the question as answered?) – Andown Aug 18 '16 at 13:13

You are using a somewhat hacky table here. Because you are trying to set the width to \celldim, you should consider that by default, every column has some additional spacing between them, which is controlled by the length \tabcolsep. So your columns would really be as wide as \celldim+\tabcolsep, but your minipage would be only \celldim-wide.

To add this to your example would mean changing \tabcolsep inside you 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}}


To illustrate what \tabcolsep does, here is a quick illustration.

### Code

\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}