开发者

Center align plain text (php)

I have been asked to come up with a solution which would allow our users to crea开发者_运维技巧te their own custom javascript dialog text. However we need it to be centered.

At the moment, we have a textarea, which the user pads using spaces and tests with a preview button. I would like to change this to allow for the text to be center aligned automatically. I think this would mean just adding the spaces myself line by line in the backend, and also adding in the correct line breaks.

The only way I can think of doing it, is getting the longest line as int, and then subtracting subsequent lines from it, and diving the result by two, and tacking that many spaces on front and back.

Is there a cleaner more elegant way to approach this problem? Are there ways of aligning text actually inside the dialog?

I had considered something like TinyMCE, but I think it's a little overkill, for what is essentially a 150 character, 4-5 line string.


On the PHP side, you can do this.

$lines=array();
foreach (explode("\n",wordwrap($str,$len=80)) as $line)
  $lines[]=str_pad($line,$len,' ',STR_PAD_BOTH);
echo implode("\n",$lines);

The Javascript version should be easy to write.


This page has a useful javascript function for center-aligning a string using padding. Assuming you're displaying plain fixed-width text (using a <pre> tag or similar) then you'll need to get the length of the longest line and pad accordingly. If not, it's just a matter of setting the css: #myDiv { text-align:center; } on the div containing the text.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜