4

I have a document with a lot of tables. I would like to change the background color of the header row, for all the tables in whole document in one go without having to change the table codes itselves. Any ideas about how to do that?

For alternating colors I use this script:

\usepackage[table]{xcolor}
\definecolor{mycolor}{HTML}{c5ebec}
\let\oldtabular\tabular
\let\endoldtabular\endtabular
\renewenvironment{tabular}{\rowcolors{2}{white}{gold}\oldtabular}{\endoldtabular}

So I need something like the script above, but only for the header row.

6

Here is a solution, with the etoolbox package. If all your tables have the same format, you can patch the tabular environment. If only some tables have a coloured header, you can use a new mytabular environment. In this case, uncomment the commented line in the preamble, and comment the patch. Also I added some vertical padding in rows with the cellspace package:

\documentclass{article}
\usepackage[table, svgnames]{xcolor} \usepackage{array}
\usepackage{cellspace}
\setlength\cellspacetoplimit{4pt}
\setlength\cellspacebottomlimit{4pt}
 \usepackage{etoolbox}
\colorlet{headercolour}{DarkSeaGreen!40}

%\newenvironment{mytabular}{\rowcolors{1}{\ifnumless{\rownum}{2}{headercolour}{white}}{}\tabular}{\endtabular}

 \AtBeginEnvironment{tabular}{\rowcolors{1}{\ifnumless{\rownum}{2}{headercolour}{white}}{}}

\begin{document}

\begin{table}
  \centering
  \begin{tabular}{|*{4}{Sc}|}
    \hline
    Column1 & Column2 & Column3 & Column4 \\
    \hline
    A & \cellcolor[gray]{0.5} & D & E \\
    \hline
            & & & F \\
    \hline
            & & & \\
    \hline
  \end{tabular}
\end{table}

\end{document} 

enter image description here

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.