[Tex/LaTex] Left margins are different for longtable and tabular

horizontal alignmentlongtablemargins

I would like to use a tabular and a longtable in my document, but the left margins are not aligned.

\documentclass[letterpaper,11pt]{article}

\usepackage{longtable}

\begin{document}

\begin{tabular}{p{2cm} p{15cm}}
entry 1 & bla bla bla bla bla \\
entry 2 & this is a tabular
\end{tabular}

\begin{longtable}{p{2cm} p{15cm}}
entry 3 & This is a longtable \\
entry 4 & with many more lines \\
entry 5 & but it isn't aligned 
\end{longtable}

\end{document}

This question is related, and so is this one.

Replacing \begin{longtable}{...} with \begin{longtable}[l]{...} in the code above doesn't seem to do anything.

By fumbling around, I found that by using \setlength{\LTleft}{18pt} my margins look pretty equal. Is there a more elegant way to have longtables left-aligned with tabulars? Can I align my tables without specifying numbers?

Best Answer

enter image description here

As pointed out by other members in the comments, you have set a width that is greater than \textwidth, in this case tabularx can be used to benefit from the total available width by setting the first column as p{2cm} and the rest of the width goes to the second column. \noindent was also necessary for tabularx.

For the longtable you can set the same, but, for the second column we have to calculate the remaining width. This is done by \dimexpr\linewidth-4\tabcolsep-2cm\relax. To understand this, imagine the row as |tabcolsep||p{2cm}||tabcolsep||tabcolsep||p{length}||tabcolsep|, then, length should be equal to \linewidth-2cm-4\tabcolsep.

Finally, I have used \toprule and \bottomrule from the booktabs package to give the tables a professional appearance.

\documentclass[letterpaper,11pt]{article}
\usepackage{tabularx,booktabs}
\usepackage{longtable}

\begin{document}

\noindent
\begin{tabularx}{\textwidth}{p{2cm} X}\toprule
entry 1 & bla bla bla bla bla \\
entry 2 & this is a tabular \\ \bottomrule
\end{tabularx}

\begin{longtable}{p{2cm} p{\dimexpr\linewidth-4\tabcolsep-2cm\relax}}\toprule
entry 3 & This is a longtable \\
entry 4 & with many more lines \\
entry 5 & but it isn't aligned  \\ \bottomrule
\end{longtable}

\end{document}