0

I wanted to create a table with alternating row colors. The whole row should be filled. It doesn't seem like a big problem, using \rowcolors. But when I customized the table with manual column separators/spaces using @{}, the trouble starts.

It looks like @{} is not changing the cell size (which is filled by \rowcolors), but just shifting the cells. So the next cell's background color is covering the previous cell's content (see (1)).

Trying to not cover anything, I tried to set \tabcolsep=0pt. This, obviously, doesn't change cell size either, so there is some (in my case unwanted) whitespace between the cells that are further apart (see (2)).

I found a workaround (see (3)), that is kind of ugly to look at (code-wise).

So I was wondering: Is there a more beautiful or even "correct" solution for alternating row colors that works correctly with @{}? Or is a workaround like this one needed?

MWE result

The MWE:

\documentclass{article}

\usepackage{array}
\usepackage[table]{xcolor}

\newcommand{\mytable}[1]{%
  \begin{tabular}{#1}
    \rule{1cm}{1pt} &
      \rule[.5ex]{1cm}{1pt} &
      \rule[1ex]{1cm}{1pt}\\
    \color{blue}\rule{1cm}{1pt}\llap{\smash{\rule[.8ex]{7pt}{7pt}}} &
      \rule[.5ex]{1cm}{1pt} &
      \rule[1ex]{1cm}{1pt}\\
  \end{tabular}}

\newcommand{\testtables}[1]{%
  \rowcolors{1}{}{}%
  \mytable{#1} \quad \rowcolors{1}{}{lightgray}
  \mytable{#1}
  \vspace{10pt}}

\setlength{\parindent}{0pt}


\begin{document}
(1) First try\par
\testtables{|m{1cm} @{}m{1cm} r}

(2) \verb|\tabcolsep=0pt|\par
\setlength{\tabcolsep}{0pt}
\testtables{| @{\hspace{6pt}}m{1cm} m{1cm} @{\hspace{12pt}}r @{\hspace{6pt}}}

(3) Workaround?\par
\testtables{| >{\hspace{6pt}}m{\dimexpr1cm+6pt\relax} m{\dimexpr1cm+6pt\relax}<{\hspace{6pt}} >{\hspace{6pt}}r<{\hspace{6pt}}}

\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.