Is it possible to define a command that takes different actions based on whether the text of its argument will occupy more than one line?

I want to have a block of text that is centered if it's only one line and justified otherwise.

  • 4
    \def\macro#1{\setbox0=\hbox{#1}\ifdim\wd0<\textwidth <centered>\else<justified>\fi}
    – Manuel
    Apr 10, 2018 at 13:55

2 Answers 2


Something like this?

enter image description here


\usepackage[showframe]{geometry}% just to make it easy to see the effect




\centerorjustify{Hello world}

\centerorjustify{A long text that will be a little shorter than the text width.}

\centerorjustify{A longer text that will be longer than a line so that we can see the effect of the macro. Yeah, I don't know what else to type in here}


The macro puts the content in an \hbox and compares its width with \linewdith and centers if it is shorter.


Just for fun:

you can mis-use the caption package for a similar behaviour





\captionof{my}{one line}

\captionof{my}{longt text over multiple lines with much longer text and even longer text so that it stretches over multiple lines}


enter image description here


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .