LyessD
LyessD

Reputation: 221

How to adapt the width of a table cell to its content?

As asked in the title, I am displaying sql query result into an html table. However when the content has a long length, it is tedious to read the whole string. This is what I get : img

You can see, like in the first col, first row, the content is longer then the cell length, and I unable to read on first sight the content. I'd like the cell to be as long as the content lenght.

There is an <input> tag in each cells, as I want to modify data directly from here and use onChange event to trigger update query.

I generate my table like this :

        $texte = "<table class='table table-bordered table-sm' ><thead>$table_header</thead>";
        $texte .= "<tbody>";

        $nb_ligne ="Nombre de lignes : ".pg_num_rows($result);

        while($row = pg_fetch_row($result)){
            $texte .= "<tr>";
            foreach ($row as $value){
                $texte .= "<td><input class='form-control' value='$value' onchange=''></td>";
            }
            $texte .= "</tr>";
        }
        $texte .= "</tbody></table>";

$table_header is define above, in a switch{} case'': where depending on which case is a different string. Exemple :

switch ($query){
            case 'Aiguillage_Etat':
                $requete = "select projet.projet_nom, aiguilalge.aig_etat from projet inner join aiguillage on aiguillage.aig_id = projet.projet_id where aiguillage.aig_etat $filtre;";
                $table_header = "<th>Nom projet</th><th>Etat aiguillage</th>";
                break;
}

And I use AJAX to change <div> content, where my table is displayed :

<div id="tableau_resultat"></div>

I tried to manipulate <th> width but I did not succeed to adapt the width to length content.

I want to learn from this, so, if possible, explain to me what I'm doing wrong here, or if my approach is lacking insight.

Upvotes: 0

Views: 511

Answers (1)

Peter B
Peter B

Reputation: 24136

The problem lies in whatever is in $table_header (which you neglected to show). You need to apply CSS white-space: nowrap to the <td> or <th> elements in that.

I recommend using a <style> to define it once, something like this:

<style type="text/css">
    .table-sm > thead > tr > th { white-space: nowrap; }
</style>

or else you will need to apply inline styles for every one of the inner <td> or <th> elements.

Upvotes: 1

Related Questions