How to set dynamically the width of a html table column according to its text content?

68,133

Solution 1

If you want the width of your td to change dynamically according to your text, then you shouldn't give any predefined width for the td element.

In this example, you can see that the first td has a long text, So all td's within the same column will have their width set according to the longest td in the same column.

In the end, it boils down to the user experience. Would the user prefer td's with varying widths or would the user prefer td's with equal dimensions where a tool-tip would show the complete text in case it's larger in length than the width of the td. That, my friend, is a choice you'll have to make :)

Solution 2

so for instance you have a div

<div  id="text" style="float:left;font-size:12px;padding-top:2px" ><?php echo $_SESSION[PROJET_REF] ?> - [<?php echo $_SESSION[MANUEL_REF] ?>]</div>

you now gone get the value of characters int and depending how many there are you add a specific with

if($("#text").text().length<=100)
{
   $('.societe').attr("width", "480px");
}
if($("#text").text().length<=200)
{
   $('.societe').attr("width", "580px");
}

and so on depending on what measures you want to use

Share:
68,133
pheromix
Author by

pheromix

Updated on November 14, 2020

Comments

  • pheromix
    pheromix over 3 years

    There is a html table :

    <table width="100%" border="0" cellspacing="0" cellpadding="0">
       <tr>
          <td width="480px"  class="societe" ><div style="float:left;font-size:12px;padding-top:2px" ><?php echo $_SESSION[PROJET_REF] ?> - [<?php echo $_SESSION[MANUEL_REF] ?>]</div>
          </td>
       </tr>
       ...
    </table>
    

    The css "societe" is :

    .societe{
    
        text-align:left;
        padding-left:23px;
        font-size:11px;
        font-weight:bold;
    
        background: url(../include/images/societe.png) repeat-x;
    
        }
    

    In the column definition : <td width="480px" class="societe" > I hard-coded the column's width to 480px. It's not very good to do that ! So how to make the width dynamically to fit with the column's text width ? Here the text is <?php echo $_SESSION[PROJET_REF] ?> - [<?php echo $_SESSION[MANUEL_REF] ?>.