Display DataTables columns at natural width

2019-08-13 10:09发布

I'm working with the DataTables library, and I'm using the autoWidth option to have DataTables set column widths automatically, as well as the Scroller plugin to fix headers and page data from the server.

This combination looks beautiful when my table has a large number of columns, but when it has just a few columns, the autoWidth setting makes them cartoonishly large.

Here's an example:

http://live.datatables.net/rizuvaza/2/edit

large columns

What I'd like is for the table to be only as wide as necessary for its content, and no wider. Sometimes this will mean that the content is too wide for the viewport and must be horizontally scrolled, and sometimes this will mean that the content is narrower than the viewport, in which case I don't want it to consume the whole horizontal space.

I've found a couple of approaches that work if I'm willing to hard-code a maximum width for the table, but doing so relies on me writing code to estimate the width of the columns myself. Obviously this is dependent on a wide variety of difficult measurements (font size, content width, etc) that I'd really rather leave up to DataTables.

Is there some way to configure DataTables, or use wrapping DOM elements and styles, such that it will always draw a table using only the width necessary?

1条回答
干净又极端
2楼-- · 2019-08-13 10:39

Well - dont know if that it was you are looking for - but if you set

#example {
    display: block;
}

and run a columns().adjust() right after initialisation

var table = $('#example')
    .DataTable()
    .columns()
    .adjust()
    .draw();

then the columns will be shrinked to the absolute minimum size.
demo -> http://jsfiddle.net/j5h9ob12/1/


Update, edited titles in the fiddle to emphasize the point.

查看更多
登录 后发表回答