CSS 表格 td 宽度 - 固定,不灵活

新手上路,请多包涵

我有一张桌子,我想在 td 上设置 30px 的固定宽度。问题是当 td 中的文本太长时,td 被拉伸的宽度超过 30px。 Overflow:hidden 在 td 上也不起作用,我需要一些方法来隐藏溢出的文本并保持 td 宽度为 30px。

 <table cellpadding="0" cellspacing="0">
    <tr>
        <td>first</td><td>second</td><td>third</td><td>forth</td>
    </tr>
    <tr>
        <td>first</td><td>this is really long</td><td>third</td><td>forth</td>
    </tr>
</table>

原文由 Richard Westington 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

这不是最漂亮的 CSS,但我得到了这个工作:

 table td {
    width: 30px;
    overflow: hidden;
    display: inline-block;
    white-space: nowrap;
}

带和不带省略号的示例:

 body {
    font-size: 12px;
    font-family: Tahoma, Helvetica, sans-serif;
}

table {
    border: 1px solid #555;
    border-width: 0 0 1px 1px;
}
table td {
    border: 1px solid #555;
    border-width: 1px 1px 0 0;
}

/* What you need: */
table td {
    width: 30px;
    overflow: hidden;
    display: inline-block;
    white-space: nowrap;
}

table.with-ellipsis td {
    text-overflow: ellipsis;
}
 <table cellpadding="2" cellspacing="0">
    <tr>
        <td>first</td><td>second</td><td>third</td><td>forth</td>
    </tr>
    <tr>
        <td>first</td><td>this is really long</td><td>third</td><td>forth</td>
    </tr>
</table>

<br />

<table class="with-ellipsis" cellpadding="2" cellspacing="0">
    <tr>
        <td>first</td><td>second</td><td>third</td><td>forth</td>
    </tr>
    <tr>
        <td>first</td><td>this is really long</td><td>third</td><td>forth</td>
    </tr>
</table>

原文由 Cᴏʀʏ 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题