我正在写一份文档,需要以下结果:
我还需要两样东西:
- 框必须适应句子,这样当我写一个短句时,框里就不会出现任何空白。
- 代码必须允许用户更改框宽度,而不是默认设置整个行宽。这样,较大的句子就可以按需要压缩。
因此我开始寻找一些有助于创建填充文本的框的选项。我想出了以下代码行:
\documentclass[11pt, a4paper]{report}
\usepackage[utf8]{inputenc}
\usepackage{microtype}
\usepackage{varwidth}
\begin{document}
\noindent\fbox{\begin{varwidth}{\linewidth}
\textbf{Assumption}: This is the box where I would like that the text were aligned with the colon when it starts a new line.
\end{varwidth}}
\end{document}
此代码示例给出以下结果:
因此,正如框中消息所述,我想知道如何对齐文本,就像第一张图片一样。实际代码已经允许通过更改来减小框宽度{\linewidth}
。{4in}
该代码还能够根据句子长度调整框和框架,而不会留下空白部分和额外空间,但代码与我正在寻找的冒号对齐不匹配。我希望你能帮助我找到最好的解决方案。如果您对代码行有任何建议,甚至有更好的策略,我将不胜感激。
非常感谢。
答案1
编辑在原作者澄清了预期输出后
\documentclass[twocolumn]{article}
\newcommand{\foo}[3][\linewidth]{%
\par\noindent
\sbox0{\fbox{\textbf{#2:}\quad#3}}%
\ifdim\wd0<#1%
\usebox0%
\else
\sbox0{\textbf{#2:}}%
\fbox{%
\copy0
\quad
\parbox[t]{\dimexpr#1-1em-\wd0-2\fboxsep-2\fboxrule\relax}{#3}%
}%
\fi
}
\begin{document}
Some random text just to show where the margins are.
Some random text just to show where the margins are.
Some random text just to show where the margins are.
\foo{Assumption}{This is a box.}
\foo{Assumption}{This is a longer box.}
\foo{Assumption}{This is a box almost one line long.}
\foo{Assumption}{This is a box more than one line long.}
\foo{Assumption}{This is the box where I would like the text
to be aligned with the colon when it starts a new line.}
\foo[.8\linewidth]{Example}{\raggedright An example with optional parameter
giving the maximal width, here set to \texttt{.8\string\linewidth}.}
\end{document}
原始答案
这有点小题大做,但你可以滥用tabularx
它。
\documentclass[11pt, a4paper]{report}
\usepackage{tabularx}
\begin{document}
\noindent
\begin{tabularx}{\linewidth}{|lX|}
\hline
\textbf{Assumption}: &
This is the box where I would like that the text were aligned with the colon
when it starts a new line.\\
\hline
\end{tabularx}
\end{document}
答案2
framed
一种利用环境和来实现的方法enumitem
。它可以跨页面。
\documentclass[11pt, a4paper]{report}
\usepackage{microtype}
\usepackage{framed}
\setlength{\FrameSep}{4pt}
\usepackage{enumitem}
\usepackage{lipsum}
\begin{document}
\begin{framed}
\begin{description}[widest = \textbf{Assumption:}, leftmargin=*, nosep]%
\item[Assumption:] This is the box where I would like that the text were aligned with the colon when it starts a new line.
\end{description}
\end{framed}
\lipsum[11]
\end{document}