2

I'm trying to find a method which allows me to have columns with automatic width which are also centered in horizontal and vertical direction, just like tabularx's X columntype just centered.

So here is was I tried so far:

\documentclass{article} \usepackage{tabularx,booktabs} \newcolumntype{Z}[0]{>{\centering\arraybackslash\let\newline\\\hspace{0pt}}X}% \begin{document} \begin{table} \begin{tabularx}{7cm}{l|X|X} & long\newline heading 1 & short heading\\ \toprule row 1 & 2314 & 2134 \end{tabularx} \end{table} \begin{table} \begin{tabularx}{7cm}{l|Z|Z} & long\linebreak heading 1 & short heading\\ \toprule row 1 & 2314 & 2134 \end{tabularx} \end{table} \end{document} 

enter image description here enter image description here

The second is already almost what I want, just the vertical centering of the third column is missing. How to fix this?

2 Answers 2

3

for vertical centering you want an m column rather than a p column to sit behind X

\documentclass{article} \usepackage{tabularx,booktabs} \newcolumntype{Z}[0]{>{\centering\let\newline\\\arraybackslash\hspace{0pt}}X}% \renewcommand\tabularxcolumn[1]{m{#1}} \begin{document} \begin{table} \begin{tabularx}{7cm}{l|X|X} & long\newline heading 1 & short heading\\ \toprule row 1 & 2314 & 2134 \end{tabularx} \end{table} \begin{table} \begin{tabularx}{7cm}{l|Z|Z} & long\linebreak heading 1 & short heading\\ \toprule row 1 & 2314 & 2134 \end{tabularx} \end{table} \end{document} 
1

Just use the makecell package and its \thead command:

 \documentclass{article} \usepackage{tabularx,booktabs, makecell} \newcolumntype{Z}[0]{>{\centering\arraybackslash\let\newline\\\hspace{0pt}}X}% \begin{document} \begin{table} \begin{tabularx}{7cm}{l|X|X} &\thead{ long\\ heading 1} & \thead{short heading}\\ \toprule row 1 & 2314 & 2134 \end{tabularx} \end{table} \begin{table} \begin{tabularx}{7cm}{l|Z|Z} &\thead{long\\ heading 1} & \thead{short heading}\\ \toprule row 1 & 2314 & 2134 \end{tabularx} \end{table} \end{document} 

enter image description here

Note that with makecell, you can easily format the content of the head cells. Let me point that you shouldn't use vertical lines with booktabs: as you can see, they do not cut the horizontal ones.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.