我正在寻找一个类似的命令,它可以使一个包含居中\makebox{text to set width}[c]{new text}
的宽度的框成为可能。text to set width
____new text____
答案1
像这样吗?
\documentclass{article}
\newlength\stextwidth
\newcommand\makesamewidth[3][c]{%
\settowidth{\stextwidth}{#2}%
\makebox[\stextwidth][#1]{#3}%
}
\begin{document}
\fbox{\makesamewidth[c]{text to set width}{new text}}
\end{document}
如果参数的顺序很重要,您可以使用xparse
:
\documentclass{article}
\usepackage{xparse}
\newlength\stextwidth
\NewDocumentCommand\makesamewidth{ m O{c} m }{%
\settowidth{\stextwidth}{#1}%
\makebox[\stextwidth][#2]{#3}%
}
\begin{document}
\fbox{\makesamewidth{text to set width}[c]{new text}}
\end{document}
使用\NewDocumentCommand
而不是\newcommand
。
答案2
calc
提供\widthof{<stuff>}
:
\documentclass{article}
\usepackage{calc}
\setlength{\parindent}{0pt}% Just for this example
\begin{document}
Here is some text that is lengthy.\par
\makebox[\widthof{Here is some text that is lengthy}][l]{Left}\par
\makebox[\widthof{Here is some text that is lengthy}][c]{Centre}\par
\makebox[\widthof{Here is some text that is lengthy}][r]{Right}\par
\makebox[\widthof{Here is some text that is lengthy}][s]{S p a c e d}
\end{document}
还有另一种尴尬的方式来实现你的目标tabular
:
\documentclass{article}
\setlength{\parindent}{0pt}% Just for this example
\makeatletter
\newcommand{\widthbox}[1]{\gdef\stext{#1}\widthbox@}
\newcommand{\widthbox@}[2][c]{%
\begin{tabular}{@{}#1@{}}
\phantom{\stext} \\[-\normalbaselineskip]
#2
\end{tabular}}
\begin{document}
Here is some text that is lengthy.\par
\widthbox{Here is some text that is lengthy}[l]{Left}\par
\widthbox{Here is some text that is lengthy}[c]{Centre}\par
\widthbox{Here is some text that is lengthy}[r]{Right}
\end{document}
答案3
答案4
最简单的方法可能是使用eqparbox
包:它定义的\eqparbox, eqmakebox, \eqframebox, \eqsavebox
命令具有与基本 LaTeX 对应命令相同的参数,只是宽度参数被替换为标签。所有具有相同标签的框的宽度都与其中最宽的框相同。此外,还有一个\eqboxwidth{tag}
长度,可用作长度参数。
对于简单的需求,小包makebox
定义了一个\makebox*{longer reference text}{shorter text}
命令。
\documentclass[12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{lipsum}
\usepackage{makebox}
\usepackage{eqparbox}
\setlength\fboxsep{12pt}
\begin{document}
\begin{tabular}{c}
\fbox{\makebox*{Blahblahblah, blahblahblah, blahblahblah…}{Blahblahblahblah}}\\\\
\fbox{\eqparbox{boxa}{Blahblahblah, blahblahblah, blahblahblah…}}\\\\
\eqframebox[boxa]{Blahblahblahblah}\\\\
\eqframebox[boxa]{Blahblahblah, blahblahblah, blahblahblah…}\\\\
\fbox{\parbox{\eqboxwidth{boxa}}{\lipsum[2]}}
\end{tabular}
\end{document}