3

Is it possible to change the div's font-size depending on how many characters are in it? I have image album titles in small fixed width div's (100px). Sometimes the album names have too many characters that they force a new line. So I was wondering if it is possible to re-size the font to keep the title on one line?

crmepham
  • 4,676
  • 19
  • 80
  • 155

2 Answers2

3

Yes, by assigning a variable to a class:

In your css:

.longstring {
  font-size: 10pt;
}
.shortstring {
  font-size: 14pt;
}

In your view

<?php
$random_number = '42';
if(strlen($div_string)>$random_number){
    $font_class = 'longstring';
}else{
    $font_class = 'shortstring';
}?>
<div class="<?php echo $font_class; ?>">
    <?php echo $div_string; ?>
</div>
Shawn Barratt
  • 472
  • 3
  • 9
  • 1
    To ensure that you'll get a "safe" size in most cases, be sure to base $random_number on the number of, say, M's that will fit within 100 pixels (as opposed to, say, i's ;-)). There are ways to do stuff like this accurately using javascript (iterate over font-sizes in a hidden div and measure its resulting width), but it's rather unseemly. – JimmiTh Jan 28 '12 at 13:22
  • 2
    You shouldn't be embedding font sizes in server side code. Apply different classes and set the font size in the css. – blm Nov 04 '15 at 22:41
1

There is not a css way to do it you can use javascript or text-overflow in css3

Mahoor13
  • 5,297
  • 5
  • 23
  • 24