首页 文章

使细胞宽度适合内容

提问于
浏览
203

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

<style type="text/css">
td.block
{
border: 1px solid black;
}
</style>
<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>

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

查看下图,第一张图像是标记产生的图像 . 第二张图是我想要的 .

enter image description here

4 回答

  • 360

    我会捅一下它 . JSfiddle of the example .

    HTML:

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

    CSS:

    td{
        border:1px solid #000;
    }
    
    tr td:last-child{
        width:1%;
        white-space:nowrap;
    }
    
  • 6

    设置

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

    会解决你的问题 .

  • 1

    对我来说,这是最好的自动调整和自动调整表及其列(使用css!important ...只有你不能没有)

    .myclass table {
        table-layout: auto !important;
    }
    
    .myclass th, .myclass td, .myclass thead th, .myclass tbody td, .myclass tfoot td, .myclass tfoot th {
        width: auto !important;
    }
    

    不要为表或表列指定css宽度 . 如果表格内容较大,则会超过屏幕尺寸 .

  • 33

    根据我能找到的所有规格,将CSS宽度设置为元素的1%或100%与父元素相关 . 尽管Blink Rendering Engine(Chrome)和Gecko(Firefox)在撰写本文时似乎处理了1%或100%(使列缩小或列填充可用空间),但根据所有CSS规范无法保证我可以找到正确渲染它 .

    一种选择是用CSS4 flex div替换表:

    https://css-tricks.com/snippets/css/a-guide-to-flexbox/

    这适用于新的浏览器,即IE11见文章底部的表格 .

相关问题