垂直居中文本的新环境

垂直居中文本的新环境

考虑以下代码:

\documentclass{article}

\usepackage[
  papersize = 50mm,
  margin = 2mm
]{geometry}

\begin{document}

\topskip0pt
\vspace*{\fill}
test
\vfill

\end{document}

为了使文本垂直居中,定义新环境的“最佳”方法是什么,即获得与上面示例相同的输出?

更新

如果我尝试以下操作,文本将进入右边缘,并且文本不会水平对齐。

\documentclass{article}

\usepackage[
  papersize = 50mm,
  margin = 2mm
]{geometry}

\newenvironment{vc}{\topskip0pt\vspace*{\fill}\noindent}{\vfill}

\begin{document}

\begin{vc}
horse, horse, horse, horse, horse, horse, horse
\end{vc}

\end{document}

输出

答案1

我从 Svend 提出的代码开始,对其进行环境化,并做了一些补充。

如果您希望\strut第一行的顶部与最后一行的基线的距离相同,那么这似乎可行。

\documentclass{article}

\usepackage[
  papersize = 50mm,
  margin = 2mm
]{geometry}
\newenvironment{vc}{\topskip0pt\vspace*{\fill}\noindent\ignorespaces}{\strut\vfill}

\begin{document}

\begin{vc}
\sloppy 
\fboxsep=-\fboxrule\smash{\fbox{\strut}}%
horse, horse, horse, horse, horse, horse, horse
horse, horse, horse, horse, horse, horse, horse
horse, horse, horse, horse, horse, horse,
\end{vc}

\end{document}

在此处输入图片描述

请注意,在最后一行添加降序字母不会改变垂直间距。\strut在第一行设置完整高度或删除相同高度也不会改变垂直间距\strut

我应该注意到,下面 David 的评论建议\noindent\ignorespaces不应将其放在环境定义中,因为它会产生其他问题。在这种情况下,删除该代码,用户需要\noindent手动将其添加到实际内容中。或者,可以重新定义\parindent,如下所示

\newenvironment{vc}{\parindent0pt\relax\topskip0pt\vspace*{\fill}}{\strut\vfill}

ignorespaces其最终效果是从环境中删除所有段落缩进,同时避免在定义中使用。

答案2

如果您希望内容打印在,您也可以将内容放在常规文本流之外。下面的示例使用eso-pic定位vc环境内包含的文本\AtPageCenter

在此处输入图片描述

\documentclass{article}

\usepackage[
    papersize = 50mm,
    margin = 2mm,
    showframe
  ]{geometry}
\usepackage{eso-pic,environ}

\NewEnviron{vc}[1][\textwidth]{%
  \clearpage
  \mbox{}
  \AddToShipoutPictureFG*{% Add only to the ForeGround of this page
    \AtPageCenter{% lower-left anchor at Page Center
      \makebox[0pt]{% horizontally centered anchor
        \parbox{#1}{\BODY}% Necessarily vertically centered anchor
      }%
    }%
  }
  \clearpage
}

\begin{document}

\begin{vc}
horse, horse, horse, horse, horse, horse, horse
\end{vc}

\end{document}

文本的默认宽度是\textwidth;可以通过为环境指定可选参数来改变vc

答案3

这主要取决于你想如何测量空间。在此代码中,距离是从顶部边框到第一行顶部(包括上升部分)以及从底部基线(忽略下降部分)到底部边距进行测量。

\documentclass{article}

\usepackage[
  papersize = 50mm,
  margin = 2mm
]{geometry}
\usepackage{microtype}

\newenvironment{vc}
  {\clearpage
   \setlength{\topskip}{0pt}%
   \setlength{\parindent}{0pt}%
   \vspace*{\fill}
   \nointerlineskip}
   {\vfill}

\begin{document}

\begin{vc}
\hrule height 0.1pt \kern-0.1pt % just for the example
abc abcg abc abcg abc abcg abc abcg
abc abcg abc abcg abc abcg abc abcg
abc abcg abc abcg
\par\vskip-\prevdepth\hrule height 0pt depth 0.1pt \kern-0.1pt % just for the example
\end{vc}

\end{document}

测量可能会出现变化。

在此处输入图片描述

相关内容