在固定宽度的颜色框中居中文本

在固定宽度的颜色框中居中文本

我怎样才能将此文本水平对齐到框的中心?


在此处输入图片描述


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\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

\parbox接受第二个强制参数,即框的内容。在您的代码中,这是\hfill。因此,有一个宽度为 4em 的空 parbox,后面跟着文本。为了显示此效果,我\parbox{4em}\hfill用一条规则替换了\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}

在此处输入图片描述

要将文本置于宽度为 4cm 的 parbox 中央,您可以使用:

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

在此处输入图片描述

答案2

不确定你为什么要这样做,但使用 很容易\makebox,默认情况下会将其内容居中。我增加了框的大小,以便它包含文本:

\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}

在此处输入图片描述

相关内容