居中,每行文字数量相等

居中,每行文字数量相等

如果我将 lorem 的第一句话居中,按照传统方式使用 center 环境将得到如下文本: lorem 居中不正确

但是,假设我想将文本居中,使得每行的长度相等。

lorem 正确居中

手动添加换行符相当容易,但这样做相当不安全。如果我更新字体大小或其他文档参数,文本很可能无法正确拆分,需要手动修复。是否可以自动执行此操作?

答案1

下面centereq将需要填充的文本宽度分数(默认值为 0.8)作为可选参数,并使线条与目标宽度相差 2em(两边各一个)。

对于足够长的段落,使用你喜欢的任何分数应该没有问题。短段落则需要有根据的猜测。

\documentclass{article}
\usepackage{kantlipsum}

\newenvironment{centereq}[1][0.8]
 {%
  \trivlist
  \centering
  \setlength{\leftskip}{\dimexpr(\columnwidth-#1\columnwidth)/2\relax plus 1em}%
  \setlength{\rightskip}{\leftskip}%
  \item\relax
 }
 {\endtrivlist}

\begin{document}

\begin{centereq}
\kant[2]
\end{centereq}

\begin{centereq}[0.6]
\kant[2]
\end{centereq}

\begin{centereq}[1]
\kant[2]
\end{centereq}

\end{document}

在此处输入图片描述

答案2

这里我提供了设置行距\centerlines[<delta length>]{<n>}{<content>}的帮助。它将内容设置在 hbox 中,并将内容宽度除以。然后创建一个宽度 +(默认 5pt)的 parbox并重置已居中的中的内容。contentnndelta length\parbox

\documentclass{article}
\usepackage[showframe,pass]{geometry}
\usepackage{fp}
\makeatletter
\newcommand\centerlines[3][5pt]{%
  \sbox0{#3}%
  \FPdiv\result{\strip@pt\wd0}{#2}
  {\noindent\hfill
  \parbox{\dimexpr #1+\result pt}{\centering\strut#3\strut}%
  \hfill\mbox{}\par}
}
\makeatother
\begin{document}
\centerlines{2}{To be or not to be, that is the question}

\centerlines[9pt]{8}{When in the Course of human events, it becomes necessary
 for one people to dissolve the political bands which have connected them 
with another, and to assume among the powers of the earth, the separate 
and equal station to which the Laws of Nature and of Nature's God entitle 
them, a decent respect to the opinions of mankind requires that they 
should declare the causes which impel them to the separation.}
\end{document}

在此处输入图片描述


这里有一个略微不同的版本。在这个版本中,\parbox不使用 a。而是使用\leftskipnad \rightskip,因此结果可能会跨页。但是,输出的每一行将\centerlines被强制为相同的宽度,并且连字符现在处于活动状态。

\documentclass{article}
\usepackage[showframe,pass]{geometry}
\usepackage{fp}
\makeatletter
\newcommand\centerlines[3][5pt]{%
  \sbox0{#3}%
  \FPdiv\result{\strip@pt\wd0}{#2}
  \FPdiv\theskip{\strip@pt\dimexpr\linewidth-\result pt-#1\relax}{2}%
  {\centering\leftskip\theskip pt\rightskip\theskip pt#3\par}
}
\makeatother
\begin{document}
\centerlines{2}{To be or not to be, that is the question}

\centerlines[1pt]{8}{When in the Course of human events, it becomes necessary
 for one people to dissolve the political bands which have connected them 
with another, and to assume among the powers of the earth, the separate 
and equal station to which the Laws of Nature and of Nature's God entitle 
them, a decent respect to the opinions of mankind requires that they 
should declare the causes which impel them to the separation.}

Back to normal
\end{document}

在此处输入图片描述

相关内容