Specifying a fixed column width in jQuery Datatables
http://stackoverflow.com/questions/25706537/specifying-a-fixed-column-width-in-jquery-datatables
HTML
<script src="//cdn.datatables.net/1.10.2/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="//cdn.datatables.net/1.10.2/css/jquery.dataTables.min.css">
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<meta charset=utf-8 />
<title>DataTables - JS Bin</title>
</head>
<body>
<div class="container">
<table id="example" class="display" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$3,120</td>
</tr>
<tr>
<td>Garrett Winters long lonnngg veryy lonnnggggg</td>
<td>Director</td>
<td>Edinburgh</td>
<td>63</td>
<td>2011/07/25</td>
<td>$5,300</td>
</tr>
<tr>
<td>Ashton Cox</td>
<td>Technical Author</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$4,800</td>
</tr>
<tr>
<td>Cedric Kelly</td>
<td>Javascript Developer</td>
<td>Edinburgh long lonnngg veryy lonnnggggg</td>
<td>22</td>
...
CSS
#example {
width: 1200px;
}
JavaScript
$('#example').DataTable({ //four column table
autoWidth: false, //step 1
columnDefs: [{
width: '100px',
targets: 0
},
{
width: '100px',
targets: 1
},
{
width: '100px',
targets: 2
},
{
width: '100px',
targets: 3
},
{
targets: [0, 1, 2, 3],
createdCell: function(cell, cellData, rowData, rowIndex, colIndex) {
var $cell = $(cell)
$(cell).contents().wrapAll("<div class='content'></div>");
//get the new class
var $content = $cell.find(".content");
//if cell data is more than cell width
$(cell).append((cellData.length * 8) + ';' + $(cell).width());
if ((cellData.length * 8) > $(cell).width()) {
// hide div except for 20px
$content.css({
"height": "20px",
"overflow": "hidden"
})
// show more button
$(cell).append($("<button class='more-button'>...</button>"));
}
$btn = $(cell).find("button");
$cell.data("isLess", true);
$btn.click(function() {
var isLess = $cell.data("isLess");
$content.css("height", isLess ? "auto" : "20px")
$(this).text(isLess ? 'Read Less' : '...')
$cell.data("isLess", !isLess)
})
}
},
]
});