leoluk
leoluk

Reputation: 12961

Shrink text to table cell

Maybe it's an easy question, but there seems to be no obvious answer.

I have a table with a fixed layout (cells can't resize without screwing up the entire layout) and some dynamic text inside some cells. In case the text overflows, the text should shrink to fit inside the cell, instead of being clipped or wrapped.

I actually expected had to be a good CSS solution, but I failed to find any. Do I really have to do this manually using JavaScript?

Any idea? (best solution would be to not put dynamic text inside a fixed layout table, of course, but in this case there's no way around).

Upvotes: 2

Views: 5524

Answers (4)

Aoryu
Aoryu

Reputation: 41

Nowadays (Original answer was 8 years ago), using "vw" instead "px" on text-size does the magic. Left this for future references to whom may need this info.

For a detailed reference of setting CSS font-size on webpages, please read this reference site - Backup.

Upvotes: 2

SierraOscar
SierraOscar

Reputation: 17637

For anyone still interested in this, I wrote a PHP function to wrap the text in a span class and control the size. You can play with the $maxLength and $divisor variables to get it right for your table and then apply the function globally:

    function ShrinkText($text)
    {
        $maxLength = 20; // The length at which to start shrinking.
        $divisor = 5; // The factor to shrink by

        /*
         * A divisor of 5 with a string of 30 would do the following:
         *
         * $diff = (30 - 20)                                     [10]
         * $multiplier = ($diff / $divisor) * 10     [(10/5)*10 = 20]
         * $percentage = 100 - $multiplier            [100 - 20 = 80]
         * 
         * Output = '<span style="font-size:80%;">' . $text . '</span>'
         *
         */

        if(strlen($text) > $maxLength)
        {
            $diff = (strlen($text) - $maxLength);
            $multiplier = ($diff / $divisor) * 10;
            $percentage = 100 - $multiplier;

            return '<span style="font-size:' . $percentage . '%;">' . $text . '</span>';
        }
        else
        {
            return $text;
        }
    }

Upvotes: 2

Ruan Mendes
Ruan Mendes

Reputation: 92274

Different font sizes on a table is going to look horrific, if acceptable, clip the text with overflow: hidden; text-overflow: ellipsis; and add a tooltip so people can see the clipped text

Upvotes: 2

Eric Rowell
Eric Rowell

Reputation: 5219

I hate to be the guy that says "you can't", but today I'll have to be that guy. Unfortunately there is no way to dynamically size text based on the length of a text string using only CSS. You'll certainly have to solve this using JavaScript.

Upvotes: 3

Related Questions