是否可以根据内容的长度动态对齐内容?

是否可以根据内容的长度动态对齐内容?

我正在为我的论文做前言。

标题页包含以下内容:

Title:            some centered text
Instructors:           somebody
...:                     ...

所以我把它们放在一个两列的表格里,第一列左对齐,第二列居中。但是当第二列有长文本(长标题或多位讲师)时,它就变成了:

Title:       some centered very very very
                    looooong text
Instructors:           somebody
...:                     ...

虽然我希望它左对齐,但如下所示:

Title:       some centered very very very
             looooong text
Instructors:           somebody
...:                     ...

答案1

这是一个概念证明。

\documentclass{article}

\newcommand{\SLcheck}[2]% #1 = width, #2 = text
{\bgroup
  \sbox0{#2}%
  \ifdim\wd0>#1\relax \parbox[t]{#1}{#2}%
  \else \usebox0
  \fi
 \egroup}

\begin{document}
\begin{tabular}{lc}
Title: & \SLcheck{4cm}{some justified very very very looooong text} \\
Instructors: & \SLcheck{4cm}{somebody}
\end{tabular}
\end{document}

下一步是使用数组包创建一个新的列类型。

\documentclass{article}
\usepackage{array}

\newenvironment{SLcheck}[1]% #1 = width
{\def\myarg{#1}% local definition
  \begin{lrbox}{0}}{\end{lrbox}%
  \ifdim\wd0>\myarg\relax \parbox[t]{\myarg}{\unhbox0}%
  \else \box0
  \fi
}

\newcolumntype{Q}[1]{>{\SLcheck{#1}}c<{\endSLcheck}}

\begin{document}
\begin{tabular}{lQ{4cm}}
Title: & some justified very very very looooong text \\
Instructors: & somebody
\end{tabular}
\end{document}

相关内容