【问题标题】:fit width of <td> to its content<td> 的宽度适合其内容
【发布时间】:2015-03-28 14:54:31
【问题描述】:

我有一个 HTML 表格,我想将第一列的宽度设置为该列单元格中最大项目的宽度。

当我将宽度设置为 50px 时,它看起来很好:

但是,如果我将宽度设置为“自动”,它会扩展得太多:

为什么会这样,我该如何解决?

这是我的代码:

<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>

编辑:
当我从 &lt;table&gt; 参数中删除 style='width:700px' 时,它似乎起作用了。

我希望表格有一个固定的宽度,因为这些表格可能不止一个,我不希望每个表格都有不同的宽度。

【问题讨论】:

  • @Huangism - 你的小提琴看起来与 mariu5 的第二张图片相同。难道他不想复制第一个的样子吗?
  • @enhzflep 是的 OP 想要第一个,我制作了小提琴来支持这个问题,它将为人们提供更轻松的时间来解决它。如果 OP 有一个小提琴,我不会做一个
  • 我认为this answers the question TL;DR 的说法是正确的,因为这是有人决定应该这样做的

标签: css html-table


【解决方案1】:

改变你的CSS如下:-

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

更新小提琴:http://jsfiddle.net/Lk6bf5mm/1/

【讨论】:

    【解决方案2】:

    根据是否将其用作响应式表格,您可以考虑为列使用 max-width 或 min-width 属性,作为之前建议的另一种替代方法。

    【讨论】:

      猜你喜欢
      • 2017-08-08
      • 1970-01-01
      • 2019-11-24
      • 2014-01-14
      • 1970-01-01
      • 2020-08-28
      • 2022-12-01
      • 2014-05-19
      相关资源
      最近更新 更多