HTML Fixed Width Table, columns won't resize

时间:2017-04-10 00:24:25

标签: html html-table cell tablelayout fixed-width

I have a div with a fixed width of 400px. There's a table inside the div that is larger than 400px, so I want the div to scroll. That works fine. but I can't change the width of the cells. I need cell 2 to be 200px wide.

<div style='width:400px;overflow:scroll'>
<table style='border:1px solid black'>
<th>field1</th>
<th style='width:200px'>field2</th>
<th>field3</th>
<th>field4</th>
<th>field5</th>
<th>field6</th>
<th>field7</th>
<th>field8</th>
<th>field9</th>
<th>field10</th>
<th>field11</th>
<th>field12</th>
<th>field13</th>
<th>field14</th>
<th>field15</th>
</table>
</div>

2 个答案:

答案 0 :(得分:3)

Add display: block. If you want table-cells to have widths, add table-layout: fixed; width: 100%; from this solution. Unfortunately, that doesn't work with your scroll functionality.

<div style='width:400px;overflow:scroll'>
<table style='border:1px solid black'>
<th>field1</th>
<th style='width:200px; display: block;'>field2</th>
<th>field3</th>
<th>field4</th>
<th>field5</th>
<th>field6</th>
<th>field7</th>
<th>field8</th>
<th>field9</th>
<th>field10</th>
<th>field11</th>
<th>field12</th>
<th>field13</th>
<th>field14</th>
<th>field15</th>
</table>
</div>

答案 1 :(得分:2)

Add nowrap attribute to your <th> element. More info aboutnowrap Attribute

<div style="width: 400px; overflow: scroll">
    <table style="border: 1px solid black">
        <th>field1</th>
        <th style="width: 200px" nowrap>field2</th>
        <th>field3</th>
        <th>field4</th>
        <th>field5</th>
        <th>field6</th>
        <th>field7</th>
        <th>field8</th>
        <th>field9</th>
        <th>field10</th>
        <th>field11</th>
        <th>field12</th>
        <th>field13</th>
        <th>field14</th>
        <th>field15</th>
    </table>
</div>