文本居中左对齐

文本居中左对齐

我需要定义一个新环境,其中包含一个以当前页面为中心且文本左对齐的小页面。

就像是:

\newenvironment{texto}{
   \begin{center} % so the minipage is centered
   \begin{minipage}[t][\textwidth]
   \begin{flushleft} % so the minipage's text is left justified
}{
   \end{flushleft}
   \end{minipage}
   \end{center}
}

我已经尝试了几个小时,但至今仍无所获。

如果可以将小页面放入新环境内的居中 makebox 中,这将是可能的,但没有 makebox 环境。

编辑:

\documentclass[a4paper,10pt,twoside,onecolumn,openright,final]{book}
\newenvironment{code-block}{
    \begin{center}
    \begin{minipage}[t]{\textwidth}
    \raggedright
}{
    \end{minipage}
    \end{center}
}

\begin{document}

a completely random line, filled with random words, or perhaps not!

\begin{code-block}
pineapples with mustard
\end{code-block}

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

\end{document}

结果:

在此处输入图片描述

答案1

允许可变宽度minipage环境,您需要varwidth包裹。 来自包装文档

该包定义了一个varwidth环境(基于minipage),它是的类似物minipage,但其结果宽度是其内容的自然宽度。

包文档中给出的最小示例说明了以下内容:

软件包文档中的 varwidth 环境示例

因此,改变Stefan 的回答方式如下:

\usepackage{varwidth}% http://ctan.org/pkg/varwidth
\newenvironment{texto}{%
  \begin{center} % so the minipage is centered
  \begin{varwidth}[t]{\textwidth}
  \raggedright % so the minipage's text is left justified
}{%
  \end{varwidth}
  \end{center}
}

varwidth 与 minipage

答案2

以下是一个建议:

\newenvironment{texto}[1][\textwidth]{
   \begin{center} % so the minipage is centered
   \begin{minipage}[t]{#1}
   \raggedright % so the minipage's text is left justified
}{
  \end{minipage}
  \end{center}
}
  • 我使用声明\raggedright而不是flushleft环境,因为效果受到外部小页面环境的限制。

  • 我为小页面的强制宽度引入了一个可选参数。

完整示例:

\documentclass{article}
\usepackage[ngerman]{babel}
\usepackage{blindtext}
\newenvironment{texto}[1][\textwidth]{
   \begin{center} % so the minipage is centered
   \begin{minipage}[t]{#1}
   \raggedright % so the minipage's text is left justified
}{
  \end{minipage}
   \end{center}
}

\begin{document}
\blindtext
\begin{texto}[6cm]
  \blindtext
\end{texto}
\blindtext
\end{document}

在此处输入图片描述

相关内容