使单元格宽度适合内容

新手上路,请多包涵

鉴于以下标记,我如何使用 CSS 强制一个单元格(列中的所有单元格)适应其中内容的宽度而不是拉伸(这是默认行为)?

 td.block {
  border: 1px solid black;
}
 <table style="width: 100%;">
  <tr>
    <td class="block">this should stretch</td>
    <td class="block">this should stretch</td>
    <td class="block">this should be the content width</td>
  </tr>
</table>

我意识到我可以对宽度进行硬编码,但我宁愿不这样做,因为该列中的内容是动态的。

看下图,第一张图片是标记生成的。第二张图是我想要的。

在此处输入图像描述

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

阅读 243
2 个回答

我不确定我是否理解你的问题,但我会尝试一下:

 td {
    border: 1px solid #000;
}

tr td:last-child {
    width: 1%;
    white-space: nowrap;
}
 <table style="width: 100%;">
    <tr>
        <td class="block">this should stretch</td>
        <td class="block">this should stretch</td>
        <td class="block">this should be the content width</td>
    </tr>
</table>

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

环境

max-width:100%;
white-space:nowrap;

会解决你的问题。

原文由 Shubham Nigam 发布,翻译遵循 CC BY-SA 3.0 许可协议

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