# How to center a text vertically, if it isn't the only line?

\vspace*{\fill} works perfectly, if there's only one line. Let's imagine I have the following text:

1. This is the first line.
2. Some random text here.
3. This has to be centered.
4. Last line.


If I put \vspace*{\fill} before and after the 3rd line, it will center between the 2nd and the 4th line. I need vspace from the top to the bottom, not between the last and next line.

• Welcome to TeX.SX. It's not really clear what's your aim. – egreg Aug 19 '18 at 21:56
• @egreg I wasn't sure either, I think what the OP wants is line three in the vertical centre of the page, exactly the same distance from the top of the page as from the bottom of the page, irrespective of how much content is above and below line three. Naturally and presumably, however, line 1 should be flush with the top margin and line 4 should be flush with the bottom margin. OP have I understood you correctly? – Au101 Aug 19 '18 at 23:04

I think you can play with parboxes.

On the second page of my example (the first one is only for comparison), you find three parboxes of the same height with different content alignment (top, center, bottom).

On the third page, you find two parboxes of the same height with top and bottom alignment (the first and the last of the page) with some text in the middle surrounded by \vspace*{\fill}s.

\documentclass{article}

\begin{document}
\noindent This is for comparison.
\vspace*{\fill}

\noindent This has to be centered.
\vspace*{\fill}

\noindent Last line.
\newpage
% three parboxes of the same height with different content alignment
\noindent\parbox[][.333\textheight][t]{\linewidth}{This is the first line.

Some random text here.

Some other random text here.

Some other random text here.}
\noindent\parbox[][.333\textheight][c]{\linewidth}{This has to be centered.}
\noindent\parbox[][.333\textheight][b]{\linewidth}{Last line.}
\newpage
% two parboxes of the same height with different content alignment with some text between them
\noindent\parbox[][.4\textheight][t]{\linewidth}{This is the first line.

Some random text here.

Some other random text here.

Some other random text here.}
\vspace*{\fill}

\noindent This has to be centered.
\vspace*{\fill}

\noindent\parbox[][.4\textheight][b]{\linewidth}{Last line.}
\end{document}


Use zero height boxes. No need to guess any length.

\documentclass{article}
\usepackage{lipsum,showframe} % just for the example

\newenvironment{zerotext}[1]
{\dimen0=\parindent
\par\noindent
\begin{minipage}[#1][0pt]{\textwidth}
\parindent=\dimen0}
{\end{minipage}}

\begin{document}

\begin{zerotext}{t}
\lipsum[2]
\end{zerotext}

\vfill

\lipsum[4]

\vfill

\begin{zerotext}{b}
\lipsum[5]
\end{zerotext}

\end{document}