Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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}
share|improve this question

2 Answers 2

up vote 3 down vote accepted

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

share|improve this answer

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

share|improve this answer
    
One should note, that \tabcolsep is now globally set to 0pt -- it should be done inside another environment or within a \begingroup...\endgroup pair –  Christian Hupfer Sep 1 at 12:01
    
@ChristianHupfer Yes, thanks. I will update the answer accordingly. –  Harald Sep 1 at 12:18
    
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 at 13:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.