1

So I have this dynamic table with names that I would like to adjust so that text does not wrap to the next line and still is visible. The easiest way would be to have the text size auto-adjust to the container width so that the height whould be the same for all cells: How it looks nowHow it looks now

How I would like it to lookHow I would prefer it to look...

Anyone has some good hints?

Of course I could always have some rigid function that changes the font-size of a specific name based on the length of the text. But I was hoping that there was some cool CSS code that could do the trick!

I know that I can automatically adjust with the canvas size with (vw) but that does not help when the width of my columns are fixed.

  • 1
    I doubt there's any trick to make a css condition based on text length (calc doesn't have any kind of strategy related to that afaik). But you can read a very similar questions with answers pointing at js solutions: https://stackoverflow.com/questions/18229230/dynamically-changing-the-size-of-font-size-based-on-text-length-using-css-and-ht – Diego D Apr 04 '22 at 13:32

1 Answers1

0

I suggest storing the preferred height of the element.

For example, say it needs to be 64px high.

then just use some javascript to lower the font size till it is equal to or less than the preferred height.

you just need to set the preferredHeight to the height you want and then just add the fixHeightFontSize class to each item you want to resize the font of

Normal Javascript

let preferredHeight = 64; // in pixels
document.querySelector('.fixHeightFontSize').each(function(index){
    document.querySelector(this).css({ 'fontSize' : 120}); // just give the font an inital large value, this is only needed for bugs.
    while(size = document.querySelector(this).height() > preferredHeight){
         let newFontSize = parseInt(document.querySelector(this).css("fontSize")) - 1;
         document.querySelector(this).css({ 'font-size' : newFontSize});
    }
});

Jquery Version

let preferredHeight = 64; // in pixels
$('.fixHeightFontSize').each(function(index){
    $(this).css({ 'fontSize' : 120}); // just give the font an inital large value, this is only needed for bugs.
    while(size = $(this).height() > preferredHeight){
         let newFontSize = parseInt($(this).css("fontSize")) - 1;
         $(this).css({ 'font-size' : newFontSize});
    }
});

I'm using jquery but you would be able to impletment this in normal javascript

Dean Van Greunen
  • 5,060
  • 2
  • 14
  • 28