【问题标题】:How to let table cells automatically take up 100% width of table with table-layout: fixed?如何让表格单元格自动占用表格布局的 100% 宽度:已修复?
【发布时间】:2015-08-04 20:30:47
【问题描述】:

我对我网站上的表格行为有以下要求:

  • 单元格永远不会有任何明确的宽度,我将根据内容将单元格大小留给浏览器
  • 整个表格的宽度不得超过 100%
  • 在某些边缘情况下,即使强制最大宽度和表格换行,总宽度仍可能超过 100%(例如在移动设备上)。在这种情况下,我希望表格的宽度为 100%,并且可以水平滚动。

要完成上述操作,请查看此JSBin

HTML:

<table>
    <thead>
    <tr>
    <th>Column one</th>
    <th>Column two</th>
    <th>Column three</th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <td>1.1</td>
    <td>2.1</td>
    <td>3.1</td>
    </tr>
    <tr>
    <td>1.2</td>
    <td>2.2</td>
    <td>3.2</td>
    </tr>
    <tr>
    <td>1.3</td>
    <td>2.3</td>
    <td>3.3</td>
    </tr>
    </tbody>
  </table>

CSS:

table {
    display: block;
    table-layout: fixed;
    overflow-x: scroll;
    max-width:100%;
    background-color: #697A09 !important;
}

th, td {
    padding: 10px;
    background-color:white;
    width:auto;
}

此设置背后的想法:表格的最大宽度仅在表格设置为 display:block 时才有效。边缘情况(小视口)的水平滚动是使用 overflow-x 结合 table-layout:fixed 完成的。

这满足了我的要求,但是有一个意想不到的问题:使用 display:block 会使表格本身使用 100% 的宽度。但是,单元格似乎并没有遵循 100%,因为我试图在示例中使用不同的背景颜色突出显示,它们占用的表格宽度远低于 100%。

我基本上想要的是让表格始终占据它所在的任何父元素的 100%,并让单元格分布在这 100% 上,而无需明确设置它们的宽度。

这样的事情可能吗?

【问题讨论】:

    标签: css layout css-tables


    【解决方案1】:

    代码可能有如下帮助:

    table {
        overflow-x: scroll;
        max-width:100%;
        background-color: #697A09 !important;
        width: 100%;
    }
    
        th, td {
        padding: 10px;
        background-color:white;
        width:auto;
    }
    

    【讨论】:

    • 谢谢,但这似乎并没有改变行为。这是添加了您的建议的版本:jsbin.com/bepuxemoda/1
    • 那里没有那个代码片段:有那个代码片段它在这里:jsbin.com/gulozu/3/edit?html,css,output
    • 谢谢,但是通过从表中删除 display:block,max-width 不再起作用,因此不满足要求 #3。
    猜你喜欢
    • 2017-07-15
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多