2

For example:

<?php
$string = 'Foo bar';

$length = strlen($string);

echo '<div style="width: '.$length.'px;">'.$string.'</div>';

The above obviously does not work, as $length is 7 and 7px is smaller than the size of the outputted text.

I also understand that font size and other factors will come into play, as well.

What I'm looking for is something like this:

<div style="width:xxx; float:left;">Label 1</div><input type="checkbox"/><br/>
<div style="width:xxx; float:left; clear:left;">Longer Label 2</div> <input type="checkbox"/><br/>
<div style="width:xxx; float:left; clear:left;">Even Longer Label 3</div> <input type="checkbox"/><br/>
Charles
  • 50,943
  • 13
  • 104
  • 142
reformed
  • 4,505
  • 11
  • 62
  • 88

3 Answers3

1

If you know the font you'll be using, you want to know about imagettfbbox().

But yeah, just dont give widths and right-align the text, or use a grid-system layout like Bootstrap or 960.gs.

moonwave99
  • 21,957
  • 3
  • 43
  • 64
0

My understanding is that your are trying to match the length of the string to the dimensions of the corresponding . As you have already indicated this is only possible if you take Font Type and Size into consideration. Assuming you would have a mono-spaced font you would have to multiply $length with a factor.

The real messy part starts if you use not mono-spaced fonts...

Steven
  • 113
  • 1
  • 5
0

Also if you set value of display property to inline-block div element behaves like a block element but it's width changes with it's containing elements display: inline-block

Mustafa Shujaie
  • 806
  • 2
  • 10
  • 18