DataTables Set Column Width

There are two ways to do so.

Just set it directly in the HTML tag with the word width. The following example set the width in the table header fields.

<table id="my-table" class="display">
    <thead>
    <tr>
        <th width="15%">Header 1</th>
        <th width="15%">Header 2</th>
        <th width="70%">Header 3</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>r1 c1</td>
        <td>r1 c2</td>
        <td>r1 c3</td>
    </tr>
    <tr>
        <td>r2 c1</td>
        <td>r2 c2</td>
        <td>r2 c3</td>
    </tr>
    <tr>
        <td>r3 c1</td>
        <td>r3 c2</td>
        <td>r3 c3</td>
    </tr>
    </tbody>
</table>
$("#my-table").dataTable({
    columnDefs: [
        {
            "targets": [0],
            "visible": true,
            "width": "15%"
        },
        {
            "targets": [1],
            "visible": true,
            "width": "15%"
        },
        {
            "targets": [2],
            "visible": true,
            "width": "70%"
        }
    ]
});

By default, the HTML table style table-layout is auto. This mean the cell will auto abject the width of the cell if needed, such as the content is one single very loooooooooooooooooooooooooooooooooooong word.

To enforce the exact width, you should change the table-layout to fixed.

<table id="my-table" style="table-layout: fixed;" class="display">
.
.
.
</table>

To make the text fit the cell without over shooting, we might need to break the word like:

<tr>
    <td style="word-wrap: break-word;">r1 c1 very Looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
    <td>r1 c2</td>
    <td>r1 c3</td>
</tr>

  • datatables/datatables_set_column_width.txt
  • Last modified: 2018/10/24 12:30
  • by chongtin