How can I force a \hspace at the beginning of a line?
The other answers here address how to use \hspace
at the beginning of the line via the \hspace*
.
An alternate way of inserting spaces of an appropriate width is to use \phantom{}
which will take up as much space as would be required by the parameter passed to it. This will adapt more easily to cases where the amount of space you are trying to insert is not just an integer multiple of 1ex
/1em
.
As barbarabeeton: mentions em
should be used for horizontal spaces, and ex
for vertical ones. A good reference is Which measurement units should one use in LaTeX?.
\documentclass[border=5pt]{standalone}
\begin{document}
\texttt{\noindent
x\hspace{3ex}y
\newline\noindent
\phantom{x}\hspace{3ex}y
}
\end{document}
Use the starred version \hspace*
.
You need to make some changes: 1) \hspace
is ignored at the beginning of a line, so you should use \hspace*
instead. 2) ex
is the height of the x
character; for proper alignment you'll need to use 0.5em
which represents the width of a character in monospaced font. 3) There's a spurious blank space in your code.
The following example presents your code with ex
, a variant with em
, and a tabbing
approach that could be also of interest:
\documentclass{article}
\begin{document}
\noindent\texttt{%
x\hspace{0.5ex}\hspace{0.5ex}\hspace{0.5ex}y
\\
\hspace*{0.5ex}\hspace{0.5ex}\hspace{0.5ex}\hspace{0.5ex}y
}
\noindent\texttt{%
x\hspace{0.5em}\hspace{0.5em}\hspace{0.5em}y
\\
\hspace*{0.5em}\hspace{0.5em}\hspace{0.5em}\hspace{0.5em}y
}
{
\ttfamily
\begin{tabbing}
\=\hspace{2em}\=\kill
\>x \>y \\
\>\> y
\end{tabbing}
}
\end{document}