HTML表格中的固定宽度列,表格布局= auto

时间:2013-01-15 19:16:48

标签: html html-table tablelayout fixed-width

当HTML表格table-layout设置为auto时,其列会自动调整大小。鉴于这种情况有没有办法保持特定列固定宽度?我尝试过使用CSS宽度 - 似乎没有任何影响。

2 个答案:

答案 0 :(得分:3)

如果您使用nth-child

,则可以使用CSS执行此操作

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

答案 1 :(得分:0)

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