10

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.

1 Answer 1

8

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

5
  • This solution gives a green background to the author when doing \maketitle! Mar 16, 2021 at 16:55
  • @StrawberryFieldsForever: Could you post a small complete code reproducing this problem?
    – Bernard
    Mar 16, 2021 at 18:00
  • Just put \maketitle right after \begin{document} in your example to see what I mean. Specifying author with the \author{<author-name>} macro in the preamble is optional. Mar 16, 2021 at 18:52
  • @Bernard: How can I edit your solution to adjust the cell widths? Is there some place I can insert a p{<width>} option?
    – Leonidas
    Sep 29, 2021 at 18:14
  • @Leonidas: Yes. Replace Sc with S{p{width}}. For X column types with tabularx it is slightly more complex, but it is well explained in the package documentation.
    – Bernard
    Sep 29, 2021 at 19:42

You must log in to answer this question.

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