Site icon texblog

Color Table Series Part 2: Xcolor Package

Series overview

  1. Introduction to colors
  2. The colortbl package
  3. The xcolor package
  4. The colortab package

 

3. The xcolor package

While coloring tables, the xcolor package provides the same commands as <a href="https://www.ctan.org/pkg/colortbl">colortbl</a>. The reason is that loading the xcolor package with the table option loads the colortbl package in the background. On top to the functionality provided by colortbl (discussed here), xcolor predefines more colors and provides a macro to set the background color for even and odd rows.

 

Loading the package

To use xcolor to color tables, load the package with the table option:

\usepackage[table]{xcolor}

To use the package with beamer, you have to change your \documentclass declaration instead:

\documentclass[xcolor=table]{beamer}

 

Alternating row colors in a table

The \rowcolors macro alternates the background color of rows in a table. Make sure it is \rowcolors with an “s” and not \rowcolor, which is defined by colortbl.

\rowcolors[<i><commands></i>]{<i><row></i>}{<i><odd-row color></i>}{<i><even-row color></i>}

This command set the odd rows’ color to <i><odd-row color></i> and the even rows’ color to <i><even-row color></i>, starting at the row number <i><row></i>. An optional <i><commands></i> is executed before each row.

% Preamble
\usepackage[table]{xcolor}

% Table code
{
	\rowcolors{2}{green!25}{green!75}
	\begin{tabular}{ccc}
		\hline
		\rowcolor{gray}Header & Header            & Header \\
		1                     & 2                 & 3      \\
		4                     & \cellcolor{gray}5 & 6      \\
		7                     & 8                 & 9      \\
		\hline
	\end{tabular}
}

\cellcolor overwrites \rowcolor, which itself overwrites \columncolor in a \multicolumn cell. On the other hand, \multicolumn overwrites \rowcolors (note the “s”), which itself overwrites \columncolor in the preamble of your table.

Finally, the <a href="https://www.ctan.org/pkg/tabu">tabu</a> package provides a more flexible command with \taburowcolors. See the package documentation for more details.


The author of this article is the main developer behind the LaTeX Complex Tables Editor.

Exit mobile version