Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fit width of <td> to its content

Tags:

css

html-table

I have an HTML table and I would like to set the width of the first column to the width of the largest item in a cell of that column.

When I set the width to 50px, it looks fine: HTML table 50px width

If I set the width to 'auto' however, it gets extended way too much: HTML table auto width

Why does it do that and how can I fix this?

Here's my code:

<html>
    <body>
        <style type="text/css">
            .tg  {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
            .tg td{font-family:Calibri, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#fff;}
            .tg th{font-family:Calibri, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#f0f0f0;}
            .tg .tg-j4kc{background-color:#efefef;text-align:center}
            .tg .tg-ud5c{background-color:#efefef;text-align:right;width:auto}
            p.italic{font-style: italic}
        </style>

        <font face="Calibri, Arial, Sans-Serif" font size="3">
            The script<br><br>

            <p class="italic">' + $ScriptName + '</p>

            has sent a notification. See below for details...
        </font><br><br>

        <table class="tg" style='width:700px'>
            <tr>
                <th class="tg-j4kc" colspan="2">Script</th>
            </tr>
            <tr>
                <td class="tg-ud5c">Path</td>
                <td>"' + $ScriptPath + '"</td>
            </tr>
            <tr>
                <td class="tg-ud5c">Server</td>
                <td>' + $Server + '</td>
            </tr>
            <tr>
                <td class="tg-ud5c">Name</td>
                <td>' + $ScriptName + '</td>
            </tr>
        </table>

        <font face="Calibri, Arial, Sans-Serif" font size="3">
            <br><u>Notification</u>
            <br><br>' + $NotificationContent + '
        </font>
    </body>
</html>

Edit:
It seems to work when I remove the style='width:700px' from the <table> argument.

I would like to have a fixed width for the table though because it can happen that there are more than one of these tables and I don't want every table to have a different width.

like image 774
mariu5 Avatar asked Mar 26 '15 14:03

mariu5


1 Answers

change your css as following :-

tg .tg-ud5c {
    background-color:#efefef;
    text-align:right;
    width:1%;
    white-space: nowrap;
}

Updated fiddle : http://jsfiddle.net/Lk6bf5mm/1/

like image 107
Bhavin Panchani Avatar answered Nov 04 '22 20:11

Bhavin Panchani