sometimes when we use Datatables, Datatables table header or column does not aligned or matched with the table body width .here are two solutions, check which one work for you-
Solution 1: table width 100%
Give your table a style of width 100% for example width=”100%”
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<table class="table table-striped" id="emptableid" width="100%"> <thead> <tr> <th>Firstname</th> <th>Lastname</th> <th>Email</th> </tr> </thead> <tbody> </tbody> </table> |
Solution 2: use DataTables fixcolumn cdn /columns.adjust()
add or use fixColumn CDN( https://cdn.datatables.net/fixedcolumns/ ) CSS and js file in your code for that
1 2 3 |
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/fixedcolumns/3.3.0/css/fixedColumns.dataTables.css"> <script type="text/javascript" src="https://cdn.datatables.net/fixedcolumns/3.3.0/js/dataTables.fixedColumns.js"></script> |
and add columns.adjust()
var
table = $(
'#example'
).DataTable();
table.columns.adjust().draw();
for example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
<!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/fixedcolumns/3.3.0/css/fixedColumns.dataTables.css"> </head> <body> <div class="container"> <h2>Striped Rows</h2> <p>The .table-striped class adds zebra-stripes to a table:</p> <table class="table table-striped" id="emptableid"> <thead> <tr> <th>Firstname</th> <th>Lastname</th> <th>Email</th> </tr> </thead> <tbody> </tbody> </table> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/fixedcolumns/3.3.0/js/dataTables.fixedColumns.js"></script> <script type="text/javascript"> $(document).ready(function() { var temployee= $("#emptableid").DataTable(); temployee.columns.adjust().draw(); }); </script> </body> </html> |
You can also write this way that part
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script type="text/javascript"> $(document).ready(function() { var temployee= $("#emptableid").DataTable({ "initComplete": function( settings, json ) { temployee.columns.adjust().draw(); } }); }); </script> |
Video Link