2

I have a table with a header row whose contents I want to be bold and centered. I also want vertical rules between each pair of columns for the entire table.

I like the solution of creating a macro for this, as suggested in this answer for create table with only header bold and center. That leaves me with this MWE:

\documentclass{article}

\newcommand*{\thead}[1]{\multicolumn{1}{c|}{\bfseries #1}}

\begin{document}

\begin{tabular}{ l | l }

  % Header row
  \thead{Left Header} & \thead{Right Header} \\

  % Non-header rows. Long cell so we can see centering working
  Top Left    & Top Right \\
  Bottom Left & Bottom Right is looooooooong

\end{tabular}

\end{document}

Output of the provided MWE

Everything looks good except for the wayward vertical rule to the right of "Right Header".

I know I can make a dedicated macro for the last header in the row, like this:

\newcommand*{\thead}[1]{\multicolumn{1}{c|}{\bfseries #1}}
\newcommand*{\theadlast}[1]{\multicolumn{1}{c}{\bfseries #1}}

but I want the invoked command to be as uniform across the row as possible... ideally the same command would be used for every column, with no variation in arguments or the command. Is there a reasonable way to do this?

Note: I'm trying to stick with the built-in tabular plus the array and tabularx packages; I'm trying to understand how to customize the built-in tabular environment without resorting to additional packages.

2
  • 1
    Why do you want to reinvent the wheel? – Bernard Feb 5 at 0:24
  • 2
    @Bernard Because throwing a package at the problem does nothing to help me understand the core tool. I don't want somebody to catch a fish for me; I want to see an example of catching a fish so I know what it looks like. – drmuelr Feb 5 at 0:49
3

You can use infinite glue that overrides the one added by default:

\documentclass{article}

\newcommand*{\thead}[1]{%
  \hspace*{0pt plus 1filll}% very infinite glue
  \bfseries % set boldface
  \ignorespaces % emulate tabular
  #1% the actual entry
  \unskip % emulate tabular
  \hspace*{0pt plus 1filll}% very infinite glue
}

\begin{document}

\begin{tabular}{ l | l }

  % Header row
  \thead{Left Header} & \thead{Right Header} \\

  % Non-header rows. Long cell so we can see centering working
  Top Left    & Top Right \\
  Bottom Left & Bottom Right is looooooooong

\end{tabular}

\end{document}

Of course the simplest way is to avoid vertical rules.

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.