[Tex/LaTex] \raggedright behavior with minipage and tabbing

horizontal alignmentminipagetabbing

In the following 3 examples a minipage with a nested tabbing environment is used to show several aligned lines of text. (This is part of a larger example.)

Output of pdflatex :

enter image description here

The first example is centered due to the center environment around it and shows the expected behavior. I do not understand the next two examples, however:

  1. Why is the second example flushed left just because text is added before the tabbing?
  2. Why does the \raggedright have to be placed before the minipage (as it does not have any effect when placed inside the minipage but before the tabbing)?

    \documentclass{article}
    
    \begin{document}
    
    \begin{center}
    
      Example 1: Centered due to missing text:\\
    
      \begin{minipage}[t][1.5cm][t]{\textwidth}
        \raggedright % Has no influence
        \begin{tabbing}
          \hspace{2cm} \= \hspace{5cm} \kill
          AAAA: \> test\\
          BBBBBBBB: \> test\\
        \end{tabbing}
      \end{minipage}
    
      {\raggedright Example 2: Flushed left by adding text:\\}%
    
      \begin{minipage}[t][2cm][t]{\textwidth}
        \textbf{-added text-}
        \begin{tabbing}
          \hspace{2cm} \= \hspace{5cm} \kill
          AAAA: \> test\\
          BBBBBBBB: \> test\\
        \end{tabbing}
      \end{minipage}
    
      {\raggedright Example 3: Flushed left without text by setting the minipage to \textbackslash raggedright:\\}
    
      \raggedright
      \begin{minipage}[t][1.5cm][t]{\textwidth}
        \begin{tabbing}
          \hspace{2cm} \= \hspace{5cm} \kill
          AAAA: \> test\\
          BBBBBBBB: \> test\\
        \end{tabbing}
      \end{minipage}
    \end{center}
    
    \end{document}
    

Best Answer

A minipage or parbox results to have the width of an inner tabbing environment only if that tabbing is the only thing inside the minipage.

So in your example

\begin{minipage}{\textwidth}
  \textbf{-added text-}
  \begin{tabbing}
    \hspace{2cm} \= \hspace{5cm} \kill
    AAAA: \> test\\
    BBBBBBBB: \> test\\
  \end{tabbing}
\end{minipage}

The width of the minipage will be \textwidth. If instead you say

\begin{minipage}{\textwidth}
  \begin{tabbing}
    \textbf{-added text-}
    \hspace{2cm} \= \hspace{5cm} \kill
    AAAA: \> test\\
    BBBBBBBB: \> test\\
  \end{tabbing}
\end{minipage}

then the result will be what you want (possibly with space missing). You can use the varwidth environment of the package with the same name:

\documentclass{article}
\usepackage{varwidth}
\begin{document}

\begin{center}
Example of text just to see that the centering will be correct

\begin{varwidth}{\textwidth}
  \textbf{-added text-}
  \begin{tabbing}
    \hspace{2cm} \= \hspace{5cm} \kill
    AAAA: \> test\\
    BBBBBBBB: \> test\\
  \end{tabbing}
\end{varwidth}
\end{center}
\end{document}

enter image description here