8

当一个 HTML 表被table-layout设置为auto它的列是自动调整大小的。鉴于这种情况,有没有办法让特定列保持固定宽度?我试过使用 CSS 宽度 - 似乎没有任何效果。

4

3 回答 3

4

如果您使用,您可以使用 CSS 执行此操作nth-child

CSS:

.table {
    table-layout:auto
}
td, th {
    border: 1px solid #999;
    padding: 0.5rem;
}
.table1 th:nth-child(1), .table1 td:nth-child(1) {
    width: 200px; /*becomes 218px with padding*/
    background: hsl(150, 50%, 50%);
}

HTML:

<h3>table 1</h3>

<table class="table1">
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>Column 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>I'm 218px wide!</td>
            <td>00001</td>
            <td>Blue</td>
        </tr>
        <tr>
            <td>I'm 218px wide!</td>
            <td>00002</td>
            <td>Red</td>
        </tr>
        <tr>
            <td>I'm 218px wide!</td>
            <td>00003</td>
            <td>Green</td>
        </tr>
    </tbody>
</table>

<p>&#160;</p>

<h3>table 2</h3>

<table>
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>Column 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>I'm 118px wide!</td>
            <td>00001</td>
            <td>Blue</td>
        </tr>
        <tr>
            <td>I'm 118px wide!</td>
            <td>00002</td>
            <td>Red</td>
        </tr>
        <tr>
            <td>I'm 118px wide!</td>
            <td>00003</td>
            <td>Green</td>
        </tr>
    </tbody>
</table>

这是一个演示:http: //jsfiddle.net/3dyhE/2/

于 2013-10-08T15:52:31.670 回答
3

使用min-width而不是width

<table style="table-layout: auto">
  <tr>
    <td style="min-width: 200px">some cell 200px width</td>
    <td>other cell, auto width</td>
    <td>other cell, auto width</td>
    <td>other cell, auto width</td>
    <td>other cell, auto width</td>
  </tr>
</table>
于 2019-01-15T11:43:26.813 回答
0

在我的情况下,我必须为所有列指定宽度,并让它们相对于填充可用宽度的表格增长,但我仍然希望一列的宽度保持固定。解决方案是width为固定宽度列设置min-width&max-width为自动宽度列设置:

table {
  table-layout: auto;
  text-align: left;
  border: 1px solid black;
  width: 100%;
}

td, th {
  border: 1px solid black;
}

.a {
  min-width: 100px;
  max-width: 100px;
}

.b {
  width: 50px;
}

.c {
  min-width: 40px;
  max-width: 40px;
}

.d {
  min-width: 80px;
  max-width: 80px;
}
<table>
  <tr>
    <th class="a">A</th>
    <th class="b">B</th>
    <th class="c">C</th>
    <th class="d">D</th>
  </tr>
  <tr>
    <td class="a">Very long text here</td>
    <td class="b">Very long text here</td>
    <td class="c">Very long text here</td>
    <td class="d">Very long text here</td>
  </tr>
</table>

于 2021-12-13T12:47:27.203 回答