[Tex/LaTex] makebox with minimum width

horizontal alignmentspacing

I use makebox to create padded texts, however when the text in the box overflows, it overlaps with the following content. To demonstrate, enter image description here

The thing I want is a box that when the text is shorter than the given width, it works just as a normal makebox, however, when the text overflows, it should act as without a makebox, like the fourth line.

To be clear, what I want is something like:

\newcommand{flexbox}[2]{%
  \ifthenelse{\lessthan{\widthof{#2}}{#1}}{%
    \makebox{#1}[l]{#2}
  }{%
    #2
  }
}

Best Answer

\documentclass{article}
\newlength{\mylen}
\newcommand{\myflexbox}[2][3em]{%
  \settowidth{\mylen}{#2}%
  \ifdim\mylen < #1
    \makebox[#1][l]{#2}%
  \else
    #2%
  \fi
}
\begin{document}
  \myflexbox{good} padding

  \myflexbox{notbad} padding

  \myflexbox{it overlaps!} padding

  it overlaps! padding

\end{document}

enter image description here

Related Question