[Tex/LaTex] Align minipage to baseline of first or last line inside minipage

boxesminipagepositioningvarwidthvertical alignment

The minipage environment has options for making the top, bottom, or center of the minipage box line up with the baseline of the surrounding text. Is there a way to make it line up to the baseline of the first or last line of text inside the minipage?

I imagine I'd use \raisebox, but how do I calculate the distance from the top of the minipage to the first line's baseline (or the bottom of the minipage to the last line's baseline)?

Update:

As indicated in the excellent answer below, minipage already does what I want. The problem I had was that the \color command was messing with the minipage in all sorts of bizarre ways. Putting a \strut at the beginning and end of the minipage didn't fix it, but everything started working once I changed \color to \textcolor:

Picture illustrating how color broke things

\documentclass{article}
\usepackage{color}
\usepackage{varwidth}
\newcommand{\sampletext}{testing (1)\\testing (2)}
\newcommand{\tmp}[2]{\fbox{\begin{varwidth}[#1]{0.8in}#2\end{varwidth}}}
\newcommand{\broken}[1]{\tmp{#1}{\color[rgb]{0,0,0.5}\sampletext}}%
\newcommand{\fixed}[1]{\tmp{#1}{\textcolor[rgb]{0,0,0.5}{\sampletext}}}%
\setlength{\parindent}{0pt}\setlength{\parskip}{\baselineskip}%
\begin{document}
with \verb|\color|:\\
before \broken{t} between \broken{c} between \broken{b} after

with \verb|\textcolor|:\\
before \fixed{t} between \fixed{c} between \fixed{b} after
\end{document}

Best Answer

The [t] and [b] optional arguments of minipage already use the baselines of the first and last line, and not the top or bottom of the surrounding box. AFAIK most of such vertical positioning options in LaTeX address baselines. Here three minipages with [t], [c] (or without) and [b] options (code below):

Result

If this wouldn't be the case I would use \raisebox{\dimexpr-\height+\ht\strutbox\relax}{<content>} and \raisebox{\dimexpr\depth-\dp\strutbox\relax}{<content>} for the first and last baseline, respectively. This depends on the content, but would be accurate if both lines contain a \strut.


Update:

About the issue with \color: This macro apparently adds some vertical space because at the beginning of minipage TeX is still in vertical mode. To avoid this use \leavevmode before \color (as \textcolor does internally). This will change to horizontal mode and avoid the misalignment. Added a \strut before \color should actually do the same, because it also starts horizontal mode.


\documentclass{article}

\usepackage{lipsum}

\begin{document}

before
\begin{minipage}[t]{1cm}
    First\\
    Middle\\
    Last
\end{minipage}
between
\begin{minipage}[c]{1cm}
    First\\
    Middle\\
    Last
\end{minipage}
between
\begin{minipage}[b]{1cm}
    First\\
    Middle\\
    Last
\end{minipage}
after

\end{document}
Related Question