[Tex/LaTex] \hfill inside a tabular environment doesn’t flush right

colortblhorizontal alignmenttables

When I put an \hfill in a tabular row colored using the colortbl package, the coloring does not extend to what I would expect the end of the row to be.

For example, the code:

\documentclass{article}
\usepackage{colortbl}
\usepackage{xcolor}

\begin{document}
\begin{tabular}{c}
  \rowcolor{black}\textcolor{white}{Sample Text}\\
  \rowcolor{black}\hfill\textcolor{white}{More Text}\\
\end{tabular}
\end{document}

produces this output:

enter image description here

I would expect it to produce something like this:

enter image description here

I'm guessing that the problem is that using \hfill is somehow changing the length of the line. Is that the case? And, if not, why does the length of the coloring change when I use \hfill?

Best Answer

You could use \hspace{0pt plus 1filll} that would override the \hfill at the end of the cell, but this would confuse the coloring as the example shows. Better stating right alignment with \multicolumn:

\documentclass{article}
\usepackage{colortbl}
\usepackage{xcolor}

\newcommand\hfilll{\hspace{0pt plus 1filll}}

\begin{document}
\begin{tabular}{c}
Sample Text\\
\hfilll More Text\\
\rowcolor{black}\textcolor{white}{Sample Text}\\
\rowcolor{black}\hfilll\textcolor{white}{More Text}\\
\rowcolor{black}\textcolor{white}{Sample Text}\\
\rowcolor{black}\multicolumn{1}{r}{\textcolor{white}{More Text}}\\
\end{tabular}
\end{document}

Keep in mind that the reverse would require two glues (one infinite and the other zero) because a glue at the end of the cell is removed (by \unskip).

enter image description here