trex trex - 2 months ago 16
CSS Question

How to set column width for DataTables

I want to set static width for all DataTables (with scroll plugin) columns.

It makes the columns wider if I set width for all

<th>
tags except one. And it doesn't work if the width is set for all tags. Plus, when I inspect via the developer tools, I don't see any
<th>
element with width
400px
. The elements have different width:
115px
,
132px
,
145px
...

Why is that? How can I set the exact width for columns?

CSS

.big-col {
width: 400px;
}


JS

var options = {
"sScrollX": "100%",
"sScrollXInner": "110%",
"bScrollCollapse": true,
"colReorder": true
};

$(document).ready(function() {
$('#example').dataTable(options);
});


Full example: http://fiddle.jshell.net/sergibondarenko/o1hoabep/8/

Also, I tried the columnDefs option, without success.

var options = {
"columnDefs": [
{ "width": "100px", "targets": "_all" }
]
};


The exact number of columns is unknown. The HTML table is built dynamically based on data from a server side.

Answer
th.big-col{
width:400px !important;
}

table#example{
table-layout:fixed;
}

The !important for the width is necessary to override any inline styles being applied by datatables, and possibly other styles being applied by jsfiddle or whatever. The table-layout:fixed; will make the table renderer prioritize the width of the cells in the first row for deciding the width of all cells in each column.

The fiddle has everything at 410 instead of 400, due to padding.

http://fiddle.jshell.net/o1hoabep/9/

https://developer.mozilla.org/en-US/docs/Web/CSS/table-layout

Comments