简体   繁体   中英

Style Dynamic Table , TD fixed width

I have a table that create dynamically tr and td .

After a bunch of td created, they lost their formatting and result "compressed" each other. How do i maintain constant width for each td created?

I tried to set td 's width attribute but after couple of insertions they compressed itself.

I need it because the table can grow up, so i need a scrolling bar to navigate. And to do that I want the td had fixed width

You need two things:

  1. For your td's, just set the min-width. It will assure you a good width because the "normal" width attribute will still shrink if there is not enough space.
  2. For the scroll bar, use the overflow attribute.

     <style> td { min-width: 150px; } table { overflow: scroll; } </style> 

For more information about the overflow attribute: www.w3schools.com/cssref/pr_pos_overflow.asp

The comment above from @Milche Patern holds the key: table-layout: fixed .

I created a JSFiddle to illustrate this: http://jsfiddle.net/UxkUC/

HTML

<div id="container">
    <table id="my-fixed-width-table">
        <tr>
            <td> Cell 0 </td>
            <td> Cell 1 </td>
            <td> Cell 2 </td>
            <td> Cell 3 </td>
            <td> Cell 4 </td>
            <td> Cell 5 </td>
            <td> Cell 6 </td>
            <td> Cell 7 </td>
            <td> Cell 8 </td>
            <td> Cell 9 </td>
        </tr>
        <tr>
            <td> Cell 0 </td>
            <td> Cell 1 </td>
            <td> Cell 2 </td>
            <td> Cell 3 </td>
            <td> Cell 4 </td>
            <td> Cell 5 </td>
            <td> Cell 6 </td>
            <td> Cell 7 </td>
            <td> Cell 8 </td>
            <td> Cell 9 </td>
        </tr>
    </table>
</div>

CSS

#container {
    width: 100%;
    overflow-x: auto;
}

#my-fixed-width-table {
    table-layout: fixed;
    width: 100%;
}

#my-fixed-width-table td {
    width: 200px;
    border: solid 1px black;
    text-align: center;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM