本文介绍了根据sprintf的字母宽度对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm attempting to align a text-based list of items for an e-mail. Basically the problem I have is that it only works with fixed-width (monospaced) fonts - I'd like a script that somehow can align it based on the width of each letter in a standard Arialish font.

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论坛上发现, m开放给其他解决方案)

(the sprintf_nbsp() may not be necessary, I just found it on the php forums, I'm open to other solutions)

推荐答案

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

Simply put, this is impossible.

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

With a fixed-width font every character has the same width, hence the name, fixed width.

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

With other fonts this is not the case. For example, you can plainly see that the i is much narrower than the M.

您不能知道用户使用哪种字体,即使您指定像 font-family:Arial 这样也不一定能起作用系统(OSX,X11等)使用不同的字体,一些用户还会覆盖字体网站的设置等。

You can't know which font the user uses, even if you specify something like font-family: Arial this may not always work, different systems (OSX, X11, etc.) use different fonts, and some users also override font website's settings, etc.

甚至如果知道用户使用哪种字体的100%的确定性,将所有内容整合到像素完美几乎是不可能的。

And even if you knew for 100% certainty which font the user uses, it would be pretty much impossible to align everything to be pixel-perfect.

所以,你有两个选择:使用一个固定宽度的字体(Consolas是标准的Windows字体看起来不错),或使用不同的布局。

So, you have two options: either use a fixed width font ("Consolas" is a standard Windows font which looks fairly good), or use a different layout.

你可能想要的是这样的: / p>

What you probably want is something like this:

<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 ),无论其包含的文本数量。

Here, every <span> is the same width (20em) regardless of the amount of text it contains.

使用空格对齐内容几乎总是一个坏主意。使用CSS不仅更清洁,而且还容易得多。

Using spaces to align stuff is almost always a bad idea. Using CSS is not only much cleaner, it's also a lot easier.

这篇关于根据sprintf的字母宽度对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 19:33