关于html table 固定列宽

.t3 {
            width: 100%;
            table-layout: fixed; 
        }

        .t3 td, .t3 th {
            white-space: nowrap;
            word-break: break-all;
            overflow: hidden;
            text-overflow: ellipsis;
        }
  • t1未经修饰的table;t2百分百宽度;t3固定列宽,文字过多显示省略号,如果table超过容器宽度,有滚动条。

完整代码如下。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .container {
            width: 500px;
            background: #ccc;
            margin: 0 auto;
            overflow: auto;
        }

        table , table td, table, th{
            border: 1px solid red;
            border-collapse: collapse;
        }

        .t1 {}

        .t2 {
            width: 100%;
        }

        .t3 {
            width: 100%;
            table-layout: fixed; 
        }

        .t3 td, .t3 th {
            white-space: nowrap;
            word-break: break-all;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>t1原始table</h2>
        <table class="t1">
            <thead>
                <tr>
                    <th>hello</th>
                    <th>world</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>faff</td>
                    <td>faff</td>
                </tr>
            </tbody>
        </table>
    <br>
    <h2>t2宽度100%</h2>
        <table class="t2">
            <thead>
                <tr>
                    <th>hello</th>
                    <th>world</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>faff</td>
                    <td>faff</td>
                </tr>
            </tbody>
        </table>
<br>
<h2>t3有滚动条</h2>
        <table class="t3">
            <thead>
                <tr>
                    <th style="width: 400px;">400px</th>
                    <th style="width: 120px;">120px120px120px120px120px120px</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>400px400px400px400px400px400px400px400px400px400px400px400px400px400px400px400px400px400px400px400px400px400px</td>
                    <td>dfasfsdfasfsdfasfsdfasfsdfasfsdfasfsdfasfsdfasfsdfasfsdfasfsdfasfsdfasfs</td>
                </tr>
            </tbody>
        </table>

    </div>
</body>
</html>
  • 运行截图
    t