107

How can I center the column when using X in tabularx environment like in this example?

\begin{tabularx}{\textwidth}{@{}lXXXXX@{}}
 1 & 2 & 3 & 4 & 5 \\   
\end{tabularx}
4
  • 4
    do you want to centre an entire column or just one row, or just one cell?
    – ArTourter
    Jan 3, 2013 at 20:33
  • Sorry... I want to center all X columns
    – Matthias
    Jan 3, 2013 at 20:36
  • Use c instead of X.
    – m0nhawk
    Jan 3, 2013 at 20:37
  • 2
    Please consider taking Huugo as the correct answer.
    – Peter
    Apr 16, 2017 at 9:45

4 Answers 4

145

I recently dealt with the same task, so here I present my solution: I defined a new columntype Y to center the cells in a tabularxenvironment.

In the preamble define:

\newcolumntype{Y}{>{\centering\arraybackslash}X}

to typeset the example simply enter

\begin{tabularx}{\textwidth}{@{}lYYYYY@{}}
 1 & 2 & 3 & 4 & 5 & 6\\   
\end{tabularx}
2
  • 2
    Would it be on topic to expand this answer to how to center a specific row? (if there is such an elegant solution to do so)
    – Zach Smith
    Dec 3, 2017 at 7:40
  • In my case this solution does not affect the last column, where the content is left-alighed. Mar 8, 2023 at 11:34
41

You have two solutions (well at least)

If you are bound to tabularx then you can use

\begin{tabularx}{\textwidth}{@{}l *5{>{\centering\arraybackslash}X}@{}}
1 & 2 & 3 & 4 & 5 & 6\\
\end{tabularx}

Alternatively you can use the tabu package which offers you a lot more flexibility:

\begin{tabu} to \textwidth {@{} l *5{X[c]}@{}}
1 & 2 & 3 & 4 & 5 & 6\\
\end{tabu}
4
  • 1
    how to do the tabularx for \ruggedright? just replacing centering doesnt work :(
    – ankhi
    Sep 26, 2014 at 19:04
  • 3
    @ankhi probably because it is spelt \raggedright! However, a solution to this question (and this really should be a separate question rather than a comment to a vaguely related one), is given in this answer which uses the same package as suggested by herbert below
    – ArTourter
    Sep 27, 2014 at 0:45
  • 1
    May I ask what the @{} is doing?
    – Raven
    Dec 16, 2017 at 14:22
  • 2
    @Raven have a look at this answer. Basically it removes spaces.
    – ArTourter
    Dec 16, 2017 at 20:14
20
\usepackage{tabularx,ragged2e}
\renewcommand\tabularxcolumn[1]{>{\Centering}p{#1}}

with ragged2e you do not need the \arraybackslash

0
4

It’s easy peasy to set cell alignment with tblr environment of the new LaTeX3 package tabularray:

\documentclass{article}

\usepackage{tabularray}

\begin{document}

\begin{tblr}{
  colspec = {@{}X[c]X[l]X[c]X[r]X[c]@{}},
  hlines, vlines,
}
  1 & 2 & 3 & 4 & 5 \\   
\end{tblr}

\end{document}

enter image description here

1
  • Wow, this is great indeed. LaTeX3 rocks!
    – Andyc
    Nov 30, 2021 at 11:23

You must log in to answer this question.

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