Here is a MWE of what I am trying to do.
\documentclass[a4paper]{article}
\usepackage{tabularx,booktabs}
\usepackage{color,colortbl}
\begin{document}
\begin{table}[htb]
\centering
\begin{tabularx}{\textwidth}{l r r r r r r r r r r r}
\toprule
A1 & A2 & A3 & A4 & A5 & A6 & A7 & A8 & A9 & A10 & A11 & A12 \\
\midrule
\rowcolor{blue} 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 \\[0pt]
1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 \\
\bottomrule
\end{tabularx}
\begin{tabularx}{\textwidth}{l r r r r r r r r r r r r r r}
\toprule
A1 & A2 & A3 & A4 & A5 & A6 & A7 & A8 & A9 & A10 & A11 & A12 & A13 & A14 & A15 \\
\midrule
\rowcolor{blue} 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 \\[0pt]
1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 \\
\bottomrule
\end{tabularx}
\end{table}
\end{document}
The first table has too long \toprule
and \bottomrule
and looks weird. I have a few questions about this.
How can I set the size of tabularx
to be the content width?
How can I set the last column to be aligned to the right (so all columns span over the table)?
How can I set the \rowcolor
to span over the whole table?
The second table in the example is too wide. Do you know any tricks to make it look better?
Best Answer
First table has long rules because
tabularx
is trying to make a tabletextwidth
-wide but there is no column with adjustable width. Same for second table, but in this case the table contents exceed thetextwidth
. You need to useX
-column specifier to allow automatic width adjustment. Try replacingwith
Note that
X
-columns are left-aligned and of equal width. To get the last column right-aligned, you can user
-column or define a new column typeR
as follows,Then use
\begin{tabularx}{\textwidth}{l *{10}X r}
or\begin{tabularx}{\textwidth}{l *{10}X R}
to make the last column right aligned.To allow for all rows of same color, you can use the
rowcolors
command fromxcolor
package. Therowcolors
command allows you to have alternating colors for odd and even rows, with the first color specfier for odd rows. You can still userowcolor
to change color of specific rows.An example with modified column-types and coloring.
Note that all
X
-columns are same width. Adjusting width can be tricky intabularx
. Instead try usingtabulary
ortabu
package.