The colortbl package
Colours table rows, columns, single cells and rules: \rowcolor, \columncolor, \cellcolor and \arrayrulecolor.
Loading the package
\usepackage[table]{xcolor}\colorbox in a cell colours only the area behind the text and leaves white gaps to the cell borders. colortbl fills the whole cell, including the space between the columns.
Load it through the option table of xcolor. \usepackage{colortbl} alone loads the older color package, which does not know colour expressions such as gray!20. The table option also provides \rowcolors for alternating row colours.
Main commands
\rowcolor{gray!30} | Colours one row; has to be the first command of the row. |
>{\columncolor{blue!10}}r | Colours a column, written in the column argument. |
\cellcolor{red!25} | Colours the cell in which it stands. |
\rowcolors{2}{gray!15}{white} | Before the table: from row 2 on, odd rows are grey and even rows white. |
\arrayrulecolor{gray} | Colour of \hline and of the vertical lines in the tables that follow. |
Complete example
\documentclass{article}
\usepackage[table]{xcolor}
\begin{document}
\begin{tabular}{l >{\columncolor{blue!10}}r r}
\hline
\rowcolor{gray!30} Item & Price & Stock \\ \hline
Apple & 0.50 & 120 \\
Banana & 0.25 & \cellcolor{red!25} 0 \\
Cherry & 3.00 & 45 \\ \hline
\end{tabular}
\bigskip
\rowcolors{2}{gray!15}{white}
\begin{tabular}{lr}
\hline
City & Population \\ \hline
Bern & 134000 \\
Graz & 292000 \\
Kiel & 247000 \\ \hline
\end{tabular}
\end{document}Compiled with pdfLaTeX from TeX Live 2023.
Pitfalls
\rowcolorafter the first cell has started gives Misplaced \noalign.- When several commands apply to one cell,
\cellcolorwins over\rowcolor, and\rowcolorover\columncolor. - The rules of
booktabshave white space above and below them. Next to a coloured row, this space stays white and shows as a gap. \rowcolorsapplies to every table after it. Put it inside a group or atableenvironment to limit it to one table.
Related pages
- How-to Color table rows, columns and cells in LaTeX
- Package
xcolor - Package
booktabs - Error Misplaced \noalign
- Error Undefined color `darkgreen'