2

I've got many tables throughout my document that I would like to be colored like this, with the first row in a dark grey, then the even rows in white and the odd rows in a light grey:

table with formatting

Currently I'm using this to achieve this:

\usepackage[table]{xcolor}
\rowcolors{2}{white}{gray!15}

\begin{tabularx}{cX}
\rowcolor{gray!50}
Row Number & Text \\
\hline
\therownum & test \\
\therownum & test \\
\therownum & test \\
\therownum & test \\
\therownum & test \\
\therownum & test \\
\end{tabularx}

I'm looking for a way to avoid having to call \rowcolors and \hline with every tabularx begin. Is there a way to do this while keeping a variable number of columns?

An interface of something like this would be ideal:

\begin{something}{cc}
Row Number & Text \\
\therownum & test \\
\therownum & test \\
\therownum & test \\
\therownum & test \\
\therownum & test \\
\therownum & test \\
\end{something}
1
  • package tabularray provides extra functionality to define the default design of tables. BTW: Welcome to TeX.SX! Please don't post code fragments. Instead, put your fragments into a complete compilable document that shows the problem.
    – cabohah
    Commented Jul 27 at 11:18

1 Answer 1

2

A solution with {NiceTabular} of nicematrix.

\documentclass{article} 
\usepackage{nicematrix}

\def\therownum{\arabic{iRow}}

\NewDocumentEnvironment{MyTable}{m}
  {
   \begin{NiceTabular}{#1}
   \CodeBefore
      \rowcolor{gray!50}{1}
      \rowcolors{3}{gray!15}{}
   \Body
  }
  {\end{NiceTabular}}

\begin{document}

\begin{MyTable}{cc}
Row Number & Text \\
\therownum & test \\
\therownum & test \\
\therownum & test \\
\therownum & test \\
\therownum & test \\
\therownum & test \\
\end{MyTable}

\end{document}

Output of the above code

2
  • Could you tell me why you've switched from tabularx to NiceTabular? I was using tabularx to grow the last cell in a row to match the columnsize. Can this functionality be retained with NiceTabular?
    – Epithet
    Commented Jul 29 at 11:32
  • If you want to use the features of the package nicematrix, you have to use one of the environments provided by nicematrix: NiceTabular, NiceTabularX, NiceMatrix, pNiceMatrix, etc. In your case, there is no point using a X column of tabularx with the data of your tabular but, with other data, it's possible, of course, to use NiceTabularX similar to the classical environment tabularx. Commented Jul 29 at 17:03

You must log in to answer this question.

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