Search code examples
htmlcssxhtmlpixelfont-size

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


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] ?>.


Solution

  • 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 :)