代码之家  ›  专栏  ›  技术社区  ›  user81993

如何强制一个div遵守其约束并将其放入溢出,而不是调整列的大小?

  •  1
  • user81993  · 技术社区  · 10 年前

    我有一个具有特定列宽的表。在其中一列中,有一个单元格可能有太多的项目无法容纳,所以我希望它在溢出时生成滚动条。不幸的是,我不知道该怎么做,因为包含项的div只会迫使表重新成形。

    下面是一个示例: https://jsfiddle.net/mcs96tax/1/

    <table>
        <tr>
            <td>
            </td>
            <td>
                <div id="scrollme" class="scrollme">
                    <!-- items go here -->
                </div>
            </td>
        </tr>
    </table>
    

    css:

    table { width:100%; }
    td { 
        height:100px;
        width:50%;
        background-color:red;
    } td:last-child { background-color:blue; }
    
    .scrollme {
        display:flex;
        white-space:nowrap;
    
        overflow:scroll;
    }
    
    .scrollme div {
        display:inline-block;
        background-color:green;
    
    }
    
    1 回复  |  直到 10 年前
        1
  •  3
  •   Aaron    10 年前

    添加 table-layout 到您的表css。

    var el = document.getElementById("scrollme");
    
    for (i = 0; i < 15; i++) {
        var item = document.createElement("div");
        item.innerHTML = "item" + i;
        el.appendChild(item);
    }
    table {
        width:100%;
        table-layout: fixed;
    }
    td {
        height:100px;
        width:50%;
        background-color:red;
    }
    td:last-child {
        background-color:blue;
    }
    .scrollme {
        display:flex;
        white-space:nowrap;
        overflow:scroll;
    }
    .scrollme div {
        display:inline-block;
        background-color:green;
    }
    <table>
        <tr>
            <td></td>
            <td>
                <div id="scrollme" class="scrollme">
                    <!-- items go here -->
                </div>
            </td>
        </tr>
    </table>