[Tex/LaTex] Table using booktabs and cellcolor looks ugly

booktabscolortblhighlightingtablestypography

When using \cellcolor in a booktabs table, I find that the output is not really appealing:

Table

I don't really care that the colored cell does not touch the lines above and below (cf. Coloring columns in a table with colortbl and booktabs), but what I find ugly is that the \cellcolor command looks bad in combination with the shortened \midrule of its header. I was originally going to ask how to simply shorten the \cellcolor in a similar way, but I guess the output would still not be very appealing since the 3 would not be centered in its background anymore.

So, here's the more basic question: what is a best practice here to make things look appealing? I do like the booktabs style, and I have a few tables in which I'd like to highlight some cells. Note that I'm not dead set on using backgrounds for the highlighting, but I can't think of a better means: using bold seems to communicate that the highlighted values are more important (while in fact they are error cases), using italics they'd be too little obvious.

Here is the corresponding MWE:

\documentclass{article}

\usepackage{booktabs}
\usepackage{colortbl}

\begin{document}

 \begin{tabular}{ccccc}
    \toprule
        \multicolumn{2}{c}{a} & \multicolumn{3}{c}{b} \\
    \cmidrule(lr){1-2}\cmidrule(lr){3-5}
        1 & 2 & \cellcolor[gray]{0.9}3 & 4 & 5 \\
    \bottomrule
\end{tabular}

\end{document}

Best Answer

\cellcolor adds padding to ensure adjacent cell backgrounds are touching each other. I believe you don't need \cellcolor at all.

\documentclass{article}

\usepackage{booktabs}
\usepackage{xcolor}

\makeatletter
\newcommand{\ccell}[3][]{%
  \kern-\fboxsep
  \if\relax\detokenize{#1}\relax
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi
  {\colorbox{#2}}%
  {\colorbox[#1]{#2}}%
  {#3}\kern-\fboxsep
}
\makeatother
\definecolor{cellgray}{gray}{0.9}
\AtBeginDocument{\setlength{\cmidrulekern}{0.3em}}

\begin{document}

\begin{tabular}{ccccc}
\toprule
\multicolumn{2}{c}{a} & \multicolumn{3}{c}{b} \\
\cmidrule(lr){1-2}\cmidrule(lr){3-5}
1 & 2 & \ccell[gray]{0.9}{3} & 4 & 5 \\
1 & 2 & \ccell{cellgray}{3} & 4 & 5 \\
\bottomrule
\end{tabular}

\end{document}

The two \kern commands make TeX thinking the default padding of \colorbox has not been added to the cell's width. Changing a bit the amount of trimming from \cmidrule ensures the mid rules cover the colored cell.

Note that the syntax of \ccell allows for directly specifying a color or also using a defined color.

enter image description here

The definition of \ccell can be simplified into

\makeatletter
\protected\def\ccell#1#{%
  \kern-\fboxsep
  \@ccell{#1}%
}
\def\@ccell#1#2#3{%
  \colorbox#1{#2}{#3}%
  \kern-\fboxsep
}
\makeatother