3

When creating highly regular tables, I'm quite fond of the custom C column type shown below that accepts a width and centers the content, without having me worry about intercolumn space messing everything up.

Now when trying to color such a cell, strange things abound:

Too much reeeed!

How can I get rid of the spurious overshoot?

\documentclass{article}
\usepackage{colortbl}
\newcolumntype{C}[1]{@{}>{\centering\arraybackslash}p{#1}@{}}
\begin{document}
\begin{tabular}{|C{2em}|C{2em}|}
\hline
a & \cellcolor{red}b \\\hline
c & d \\\hline
\end{tabular}
\end{document}

2 Answers 2

6

Instead of using @{} to avoid the separation space in the columntype (or additionally, if you want to keep it), you could use \setlength{\tabcolsep}{0pt} instead. This eliminates the color bleed. As this would be a global option you have to put the table in another environment to avoid side effects to other tables.

% from question
\newcolumntype{C}[1]{@{}>{\centering\arraybackslash}p{#1}@{}}
\begin{tabular}{|C{2em}|C{2em}|}
\hline
a & {\cellcolor{red}}b \\ \hline
c & d \\ \hline
\end{tabular}

% implemented answer
{
  \setlength{\tabcolsep}{0pt}
  \newcolumntype{C}[1]{@{}>{\centering\arraybackslash}p{#1}@{}}
  \begin{tabular}{|C{2em}|C{2em}|}
  \hline
  a & {\cellcolor{red}}b \\ \hline
  c & d \\ \hline
  \end{tabular}
}

enter image description here

4
  • One should note, that \tabcolsep is now globally set to 0pt -- it should be done inside another environment or within a \begingroup...\endgroup pair
    – user31729
    Sep 1, 2014 at 12:01
  • @ChristianHupfer Yes, thanks. I will update the answer accordingly.
    – Harald
    Sep 1, 2014 at 12:18
  • 1
    But this only work if all columns are of type C (which is fair enough). Is there a way to change \tabcolsep only for C columns (other than using \columncolor)?
    – Fritz
    Sep 1, 2014 at 13:54
  • This works exact for me. Thanks!
    – maple
    Dec 21, 2022 at 16:01
4

Okay, you have to set the colortbl overhang of the column to 0pt to match the @{} specification. As a side effect this will give all C cells an opaque white background:

\newcolumntype{C}[1]{@{}>{\columncolor{white}[0pt]\centering\arraybackslash}p{#1}@{}}

Correct coloring

Or in case you want to work with non-zero intercolumn space:

\newcolumntype{C}[1]{@{\hspace{10pt}}>{\columncolor{white}[10pt]\centering\arraybackslash}p{#1}@{\hspace{10pt}}}

Coloring with spacing

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .