仅将句子的一部分居中,而忽略其余部分

仅将句子的一部分居中,而忽略其余部分

假设我有一些文本需要居中,而后面的文本(在同一行)应该被忽略。如何在 latex 中实现这一点?

代码的 Latex 渲染

上图中的第二行应该像第一行一样居中。第三行表示使用以下方法进行的反复试验\widthof

\documentclass{scrartcl} 
\usepackage{tcolorbox} 
\usepackage{calc}

%text that matters
\newcommand{\ImportantPart}{This part should be centered }

%text that doesn't matter
\newcommand{\IgnoredPart}{\textcolor{red}{while this doesn't matter}}

\begin{document}
%push box to bottom, let page no serve as a visual centerline marker
\null\vfill
%draw a box for visual aid
\begin{tcolorbox}



%this is how the centering should be done, regardless of what follows the important part
%the \IgnoredPart isn't printed here to illustrate
\centering \ImportantPart\\

%this is what it prints out to be
%centering gets applied to the whole sentence
{\centering \ImportantPart}\IgnoredPart\\


%the trial and error hack using \hspace
%not perfect
\centering \hspace{\widthof{\IgnoredPart}}\ImportantPart \IgnoredPart\\





\end{tcolorbox}
\end{document}

答案1

\documentclass{scrartcl} 
\usepackage{tcolorbox} 
\usepackage{calc}

%text that matters
\newcommand{\ImportantPart}{This part should be centered}

%text that doesn't matter
\newcommand{\IgnoredPart}{\makebox[0pt][l]{ \textcolor{red}{while this doesn't matter}}}

\begin{document}
%push box to bottom, let page no serve as a visual centerline marker
\null\vfill
%draw a box for visual aid
\begin{tcolorbox}



%this is how the centering should be done, regardless of what follows the important part
%the \IgnoredPart isn't printed here to illustrate
\centering \ImportantPart

%this is what it prints out to be
%centering gets applied to the whole sentence
 \ImportantPart\IgnoredPart

\ImportantPart

\end{tcolorbox}
\end{document}

将物品放在零宽度框中

在此处输入图片描述

答案2

将不需要的部分的副本放置在\phantom您想要居中的位置的另一侧:

在此处输入图片描述

\documentclass{article} 

\usepackage[margin=1in,showframe]{geometry}% For reference
\usepackage{xcolor}

%text that matters
\newcommand{\ImportantPart}{This part should be centered}
%text that doesn't matter
\newcommand{\IgnoredPart}{\textcolor{red}{while this doesn't matter}}

\begin{document}

\centering
%this is how the centering should be done, regardless of what follows the important part
%the \IgnoredPart isn't printed here to illustrate
\ImportantPart

%this is what it prints out to be
%centering gets applied to the whole sentence
\ImportantPart~\IgnoredPart


% Using \phantom
\phantom{\IgnoredPart~}\ImportantPart~\IgnoredPart

\end{document}

答案3

另一个解决方案是使用\rlap命令。当然,您需要检查最后一句是否溢出到边距中:

\documentclass{scrartcl}
\usepackage{tcolorbox}

\begin{document}
%push box to bottom, let page no serve as a visual centerline marker
\null\vfill
%draw a box for visual aid
\begin{tcolorbox}

\centering This part should be centred \\

 \centering This longer part should be centred \rlap{\quad\color{red}this one be ignored}\\

\centering This part should be centred \rlap{\quad\color{red}this one be ignored too}\\

\end{tcolorbox}

\end{document}

在此处输入图片描述

相关内容