# tabular automatic p width and right alignment

I am customizing a letter and I want to place a tabular with a multirow on the right side, here is a MWE:

\documentclass{article}
\begin{document}
\noindent
Text \\
\hrule
\hfill \begin{tabular}{r p{2cm}}
A & first line \newline second line \\
B & text
\end{tabular}
\end{document}


How can I set the column width of the p-column to the smallest possible value? I tried \width but it messes up the tabular.

I have seen people suggesting to use tabularx, but then I would have to specify the width of the table itself, and hfill doesn't properly align it to the right anymore. But I want both the table and the p-column to be the smallest width possible and the table aligned to the right!

EDIT: Also, A should be aligned with the first line of the multi-row.

• "smallest (possible) width" = "width of longest (single) line in column"? – Alexander Wittmann Oct 15 '17 at 11:53
• @AlexanderWittmann Yes – Hyperplane Oct 15 '17 at 11:55

Personally I would suggest the following to produce the table.

\documentclass{article}
\usepackage{makecell}
\begin{document}
\hfill \begin{tabular}{r l}
A & \makecell[l]{first line\\ second line} \\
B & text
\end{tabular}
\end{document}


By using an l column the width is minimal (fits the length of the longest entry) and with the usage of makecell you can determine where linebreaks should occure.

As pointed out by Schweinebacke in the comments, one can replace \makecell[l] by \makecell[tl] to vertically align 'A' and 'first line'.

• Hm this centers A with respect to the multi-cell. I'd prefer that the A is aligned with the first line as in the MWE. – Hyperplane Oct 15 '17 at 11:58
• @Hyperplane: Please read the makecell manual. \makecell provides not only l for the optional argument but, e.g., also t. You can combine them to lt or tl. – Schweinebacke Oct 15 '17 at 12:03
• @Schweinebacke Thank you. This is exactly what I want. – Hyperplane Oct 15 '17 at 12:06

If you don't want to use makecell, you could use two table rows:

\documentclass{article}
\begin{document}
\noindent
Text \\
\hrule
\hfill \begin{tabular}{rl}
A & first line \\
& second line \\
B & text
\end{tabular}
\end{document}


or use a tabular inside a tabular:

\documentclass{article}
\begin{document}
\noindent
Text \\
\hrule
\hfill \begin{tabular}{rl}
A & {\begin{tabular}[t]{@{}l@{}}first line \\
second line
\end{tabular}}\\
B & text
\end{tabular}
\end{document}