1

How can I align this text, horizontally, to the center of the box?


enter image description here


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\documentclass[margin=0mm,border=0]{standalone}
\usepackage{tikz}
\setlength{\tabcolsep}{0pt}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{tabular}{c}
    \colorbox{red}{\parbox{4em}\hfill\textcolor{white}{``hello, world''}}
\end{tabular}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{document}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1
  • 1
    Please add some background information on the purpose of this box. Is the intention to use it inside of a table for example to color a table cell? If so, why not use the features of colortbl instead? Or is the ox intended to be used as it is in the text? If so, why not go for tcolorbox?
    – leandriis
    Commented Nov 16, 2019 at 17:37

2 Answers 2

2

\parbox takes a seocond mandatory argument with the contents of the box. In your code this is \hfill. So there is an empty parbox with 4em width followed by the text. To show this effect, I have replaced \parbox{4em}\hfill by a rule \rule{4em}{1em}:

\documentclass[margin=0mm]{standalone}
\usepackage{xcolor}
\setlength{\tabcolsep}{0pt}

\begin{document}
\begin{tabular}{c}
  \colorbox{red}{\parbox{4em}\hfill\textcolor{white}{``hello, world''}}\\
  \colorbox{red}{\rule{4em}{1em}\textcolor{white}{``hello, world''}}
\end{tabular}
\end{document}

enter image description here

To center the text in the parbox with width 4cm you can use:

\documentclass[margin=0mm]{standalone}
\usepackage{xcolor}
\begin{document}
\colorbox{red}{\parbox{4em}{\centering\textcolor{white}{``hello, world''}}}
\end{document}

enter image description here

1

Not sure why you want to have that, but it's easy using \makebox, which centres its contents by default. I increased the size of the box, so that it contains the text:

\documentclass[margin=0mm,border=0]{standalone}
\usepackage{tikz}
\setlength{\tabcolsep}{0pt}

\begin{document}

\begin{tabular}{c}
    \colorbox{red}{\makebox[6em]{\textcolor{white}{``hello, world''}}}
\end{tabular}

\end{document}

enter image description here

You must log in to answer this question.

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