基于字母宽度与sprintf对齐

时间:2012-02-06 20:21:02

标签: php email printf text-formatting

我正在尝试对齐电子邮件的基于文本的项目列表。基本上我遇到的问题是它只适用于固定宽度(等宽字体)字体 - 我想要一个脚本,它可以根据标准Arialish字体中每个字母的宽度以某种方式对齐它。

function sprintf_nbsp() {
   $args = func_get_args();
   return str_replace(' ', ' ', vsprintf(array_shift($args), array_values($args)));
}
$format = '%-6s%-\'.35.35s...%\'.10s<br>';
$str = sprintf_nbsp($format, '1', 'A list of items - this is the first', '$49.99');
$str .= sprintf_nbsp($format, '100', 'This is something else', '$4.99');
$str .= sprintf_nbsp($format, '5', 'A book', '$499.99');
$str .= sprintf_nbsp($format, '16', 'Testing the function', '$49.99');
echo '<div style="font-family:Courier">'.$str."</div>";
echo '<br><br>'.$str;

(sprintf_nbsp()可能没有必要,我刚刚在php论坛上找到它,我对其他解决方案持开放态度)

1 个答案:

答案 0 :(得分:3)

  

固定宽度(等宽字体)字体 - 我想要一个不知何故可以的脚本   根据标准Arialish中每个字母的宽度对齐它   字体。

简单地说,这是不可能的。

使用固定 -width字体,每个字符的宽度都相同,因此名称为固定宽度。

对于其他字体,情况并非如此。例如,您可以清楚地看到iM窄得多。

您无法知道用户使用哪种字体,即使您指定的内容类似font-family: Arial这可能并不总是有效,不同的系统(OSX,X11等)使用不同的字体,而某些用户也会覆盖字体网站的设置等

即使 if 你知道100%确定用户使用哪种字体,也几乎不可能将所有内容对齐为像素完美。

因此,您有两种选择:使用固定宽度字体(“Consolas”是标准的Windows字体看起来相当不错),或者使用不同的布局。

你可能想要的是这样的:

<style>
  span { display: block; width: 20em;}
</style>

<span>Some text</span>
<span>Hello, world!</span>
<span>A swallow could not carry a coconut</span>

此处,每个<span>都是相同的宽度(20em),无论其包含的文字数量如何。

使用空格来对齐东西几乎总是一个坏主意。使用CSS不仅更清晰,而且更容易。