Column width not working

Column width not working

michaelkaldeckmichaelkaldeck Posts: 11Questions: 4Answers: 0
edited April 2017 in Free community support

Hi I have read the other posts in the forum. Did not find solution.

<--!  Datatables spezific files:-->
    <link href="~/datatables/dataTables.bootstrap.min.css" rel="stylesheet" />
    <script src="~/datatables/jquery.dataTables.min.js"></script>
    <script src="~/datatables/dataTables.bootstrap.min.js"></script>*

<div id="datatablestest" style="width: 460px;margin: 0 auto;">
    <table id="datatableresult" class="table table-condensed table-striped table-bordered  table-hover" cellspacing="0">       
    </table>
</div>
var daTable = $('#datatableresult').DataTable({
    "ajax": {
        "url": daUrl,
        "dataSrc": ''
    },
    "autoWidth" : false,
    "columns": [
        { data: "JourID", title: "JourID", width: '50px'},
        { data: "JourTime", title: "JourTime", width: '50px'},
        { data: "Zust1", title: "Zust1", width: '30px'},
        { data: "Dokname", title: "Dokname", width: '100px'},
        { data: "Doktype", title: "Doktype", width: '100px'},
        { data: "JourInhaltTextOnly", title: "JourInhaltTextOnly", width:'550px'},

    ],
    "paging": false,
    "scrollY": 400,
    "scrollX": true,
});

Has no effect at all.
DataTables makes column width that have nothing to do with the set options.
Am I misunderstanding completely, how this works ?
Thanks for Info
Cheers, Michael

This question has an accepted answers - jump to answer

Answers

  • michaelkaldeckmichaelkaldeck Posts: 11Questions: 4Answers: 0

    Hi all
    the only solution i found was in setting the th width AFTER generating the grid like $('thead > tr> th:nth-child(6)').css({ 'min-width': '550px', 'max-width': '550px' });.

    So the question remains, what the functionality of the width: '100px' in the colums / columndefs is.
    https://datatables.net/reference/option/columns.width talks of small deviations. But in my example (column with large wrapping text) it is completely different.
    Thanks for clarifiying .
    Regards Michael

  • tangerinetangerine Posts: 3,108Questions: 24Answers: 364

    The div containing your table has a width of 460px, but your column widths total roughly twice that. I don't understand why you're doing that.

  • michaelkaldeckmichaelkaldeck Posts: 11Questions: 4Answers: 0
    edited April 2017

    it is typical for a situation I often have. Even with a 960 body I might have 7 - 12 cols, some quite large because they must not be wrapped (like long UNC path), and some texcols with much text wrapped but rel. wide for legibility. And I must be able to scroll horiz.

    And basically the question remains, what the width options in the def of a colum means.

  • kthorngrenkthorngren Posts: 13,773Questions: 25Answers: 3,242

    I created a quick test case essentially copying what you have and it looks ok to me:
    http://live.datatables.net/jatazeho/1/edit

    It was handy that your table has the same number of columns as the built-in JS BIN table :smile:

    It uses bootstrap 3.3.7, your div and table config and your Datatables config. I have autowidth: false commented because it seems to be causing a problem with the column layout.

    Please update as needed to recreate your problem.

    Kevin

  • michaelkaldeckmichaelkaldeck Posts: 11Questions: 4Answers: 0

    Hi Kevin
    Thanks a lot for looking into it.

    I changed my test, so I get the data from an already existing HTHL Table, as in your test on http://live.datatables.net/jatazeho/1/edit

    Then the column width are generated correctly.

    If I have the data coming from a json array, as in my original example, the problem remains: column width in DataTables generated html differ considerable from columwidth in option.

    So in this case the problem remains. Or I am doing something completely wrong.

    Thanks anyway
    Michael

  • allanallan Posts: 54,680Questions: 1Answers: 8,552 Site admin
    Answer ✓

    And basically the question remains, what the width options in the def of a colum means.

    The way the column widths work in DataTables is that DataTables will create a "worst case" table when it is initialised (and if columns.adjust() is called). The worst case table takes the longest string from each column and puts them all on a single row - so the table (which is hidden btw) has the header, a single body row with all the longest strings and the footer. The widths given are then applied to that table and the actual widths are read back from it.

    It does this to try and avoid column widths jumping when paging through the table.

    In short, the widths you give are used, but if the table's content doesn't fit into them, or they don't add up correctly, the browser and DataTables will overrule you and use the widths only as a guide.

    If you absolutely want pixel perfect control over the widths you need to use table-layout: fixed; in your CSS.

    Also, don't disable the autoWidth option, particularly when scrolling. The browser can do all sorts of odd then then, such as that which you are seeing.

    Allan

  • brettbgb1brettbgb1 Posts: 1Questions: 0Answers: 0

    I was able to use max-width to force a column to be a certain width.

  • craigmccraigmc Posts: 3Questions: 1Answers: 0

    I would tend to think that with a horizontal scroll enabled the given col width should override the calculated widths?

  • newcliquenewclique Posts: 8Questions: 1Answers: 0

    It appears that in datatables.net v1.10.20 there is no such property as table-layout.

  • colincolin Posts: 12,600Questions: 0Answers: 2,154

    There's no change with table-layout, it's the same 1.10.20.

    Colin

  • RobinGroeneveltRobinGroenevelt Posts: 1Questions: 0Answers: 0

    I tried all solutions I could find on the web. Nothing worked.
    What did work for me was to wrap my data in the column definition in an html object and then to limit the width of that by using a class

    {
    data: 'pageUrl',
    title: 'Page URL',
    render: function (data) {
    return '<label class="limit-width">' + data + '</label>';
    }
    }

    .limit-width {
    max-width: 700px;
    word-wrap: break-word;
    }

  • systemsNatusystemsNatu Posts: 11Questions: 4Answers: 0

    Set width not work

    there is my code

    if ($.fn.DataTable.isDataTable('#example')) {
    table.state.clear();
    //table.dataTable().clear();
    table.destroy();
    table.MakeCellsEditable("destroy");
    $("#example tbody").empty();
    }* *

    table = $('#example').DataTable({
    ajax: {
    "url": domain + '/api/GetAllLocationInfoDetail',
    "type": "GET",
    "dataSrc": "",
    },
    //autoWidth: true,
    autoWidth: true,
    //Paginate: false,
    deferRender: true,
    scrollY: 700,
    scrollX: true,
    //sScrollX: "100%",
    "sScrollXInner": "150%",
    scrollCollapse: true,
    paging: true,
    lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
    pageLength: 25,
    stateSave: true,
    processing: true,
    //bLengthChange: false,
    'sPaginationType': 'ellipses',
    fixedColumns: {
    leftColumns: 3
    },
    language: {
    "url": "http://cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Japanese.json",
    "processing": "処理中...",
    "lengthMenu": "MENU 件表示",
    "zeroRecords": "データはありません。",
    "info": " TOTAL 件中 START から END まで表示",
    "infoEmpty": " 0 件中 0 から 0 まで表示",
    "infoFiltered": "(全 MAX 件より抽出)",
    "infoPostFix": "",
    "search": "部分検索:",
    "url": "",
    "paginate": {
    "first": "先頭",
    "previous": "前",
    "next": "次",
    "last": "最終"
    },
    select: {
    rows: {
    _: "%d行選択しました",
    0: "",
    1: "1行選択しました"
    }
    }
    },
    dom: '<"top"lf>irpt<"bottom"B>',
    buttons: [
    {
    extend: 'excelHtml5',
    text: 'Excel出力',
    footer: true,
    filename: '360°Viewer-保管場所マスタ',
    exportOptions: {
    //columns: ':visible:not(:eq(0))'
    columns: "thead th:not(.noExport)"
    }
    },
    {
    extend: 'cexcelImport',
    text: 'Excel取込'
    },
    {
    extend: 'colvis',
    text: '表示列選択'
    },
    {
    extend: 'cupdate',
    text: '登録'
    },
    {
    extend: 'cdelete',
    text: '削除'
    }
    ],
    initComplete: function () {

                var api = this.api();
    
                $(this).on('click', "i.fa.fa-plus-square", function (e) {
    
                    var currentPage = api.page();
    
                    var text = '[{"Id":"DT_RowId","ORGANIZATION_ID": "DOC_0001","LOCATION_ID": "","LOCATION_B": "","LOCATION_F": "","LOCATION_A": "","STORE_TYPE": "0","DESCRIPTION": "","LOCATION_TYPE": "11","LOCATION_TYPE_NAME": null,"LOCATION_X":0,"LOCATION_Y": 0,"LOCATION_Z": 0,"COLOR_R": 0,"COLOR_G": 0,"COLOR_B": 0,"LEADER_POS_TOP": 0,"DIFF_X_TOP": 0,"DIFF_Y_TOP": 0,"DIFF_Z_TOP": 0,"LEADER_BREAK_TOP": 0,"LEADER_POS_360": 0,"DIFF_X_360": 0,"DIFF_Y_360": 0,"DIFF_Z_360": 0,"LEADER_BREAK_360": 0,"SHELVES_COUNT": 0,"CAMERA_ANGLE": 0,"CREATE_ID": "SYSTEM","UPDATE_ID": null,"CREATE_DATE": null,"UPDATE_DATE": null,"DATA_STATUS": "N","LABEL_DEFAULT_POS_X": 0,"LABEL_DEFAULT_POS_Y": 0,"LABEL_DEFAULT_POS_Z": 0,"LABEL_AXIS_Y": 0,"LABEL_ANGLE": 0}]';
    
                    var data = JSON.parse(text);
    
                    api.row
                        .add(data[0])
                        .draw();
    
                    //move added row to desired index (here the row we clicked on)
                    var index = api.row(this).index(),
                        rowCount = api.data().length - 1,
                        insertedRow = api.row(rowCount).data(),
                        tempRow;
    
                    insertedRow["Id"] = "DT_RowId" + rowCount;
    
                    for (var i = rowCount; i > index + 1; i--) {
                        tempRow = api.row(i - 1).data();
                        api.row(i).data(tempRow);
                        api.row(i - 1).data(insertedRow);
                    }
                    //refresh the page
                    api.page(currentPage).draw(false);
    
    
                });
    
                $(this).on('change', "select.team_ddl", function (e, d) {
                    var sel = $(this)[0],
                        index = $(this).parent().parent()[0].rowIndex - 1,
                        opt = sel.options[sel.selectedIndex];
                    api.cell(index, 11).data(opt.value).draw();
                    api.cell(index, 12).data(opt.text).draw();
                });
            },
            aoColumns  : [
                //{ data: 'check', defaultContent: '' },
                { data: 'Id', "sWidth": "300px" },
                null,
                {
                    "data": null, "sortable": false,
                     "sWidth": "300px",
                    render: function (data, type, row, meta) {
                        return data.Id;
                    }
                },
            { data: 'ORGANIZATION_ID', "sWidth": "300px"},
            { data: 'LOCATION_ID', "sWidth": "300px"},
            { data: 'LOCATION_B', "sWidth": "300px"},
            { data: 'LOCATION_F', "sWidth": "300px"},
            { data: 'LOCATION_A', "sWidth": "300px"},
            { data: 'STORE_TYPE', "sWidth": "300px"},
            { data: 'DESCRIPTION', "sWidth": "300px"},
            { data: 'LOCATION_TYPE', "sWidth": "300px"},
            { data: 'LOCATION_TYPE', "sWidth": "300px"},
            { data: 'LOCATION_TYPE_NAME', "sWidth": "300px" },
            { data: 'LOCATION_X', "sWidth": "300px"},
            { data: 'LOCATION_Y', "sWidth": "300px"},
            { data: 'LOCATION_Z', "sWidth": "300px"},
            { data: 'COLOR_R', "sWidth": "300px"},
            { data: 'COLOR_G', "sWidth": "300px"},
            { data: 'COLOR_B', "sWidth": "300px"},
            { data: 'LEADER_POS_TOP', "sWidth": "300px"},
            { data: 'DIFF_X_TOP', "sWidth": "300px"},
            { data: 'DIFF_Y_TOP', "sWidth": "300px"},
            { data: 'DIFF_Z_TOP', "sWidth": "300px"},
            { data: 'LEADER_BREAK_TOP', "sWidth": "300px"},
            { data: 'LEADER_POS_360', "sWidth": "300px"},
            { data: 'DIFF_X_360', "sWidth": "300px"},
            { data: 'DIFF_Y_360', "sWidth": "300px"},
            { data: 'DIFF_Z_360', "sWidth": "300px"},
            { data: 'LEADER_BREAK_360', "sWidth": "300px"},
            { data: 'SHELVES_COUNT', "sWidth": "300px"},
            { data: 'CAMERA_ANGLE', "sWidth": "300px" },
            { data: 'CREATE_ID', "sWidth": "300px"},
            { data: 'UPDATE_ID', "sWidth": "300px"},
            { data: 'CREATE_DATE', "sWidth": "300px"},
            { data: 'UPDATE_DATE', "sWidth": "300px"},
            { data: 'DATA_STATUS', "sWidth": "300px"},
            { data: 'LABEL_DEFAULT_POS_X', "sWidth": "300px"},
            { data: 'LABEL_DEFAULT_POS_Y', "sWidth": "300px"},
            { data: 'LABEL_DEFAULT_POS_Z', "sWidth": "300px"},
            { data: 'LABEL_AXIS_Y', "sWidth": "300px"},
            { data: 'LABEL_ANGLE', "sWidth": "300px"}
            ],
            columnDefs: [
                {
                    'targets': 0,
                    "orderable": false,
                    "sortable": false,
                    'checkboxes': {
                        'selectRow': true
                    }
                },
                {
                    targets: 1,
                    type: "dom-text",
                    "searchable": false,
                    "orderable": false,
                    "className": "dt-center",
                    render: function (data, type, row, meta) {
                        return "<i class=\"fa fa-plus-square\" aria-hidden=\"true\"></i>";
                    }
                },
                {
                    targets: 10,
                    "searchable": false,
                    "sortable": false,
                    render: function (data) { return createSelect(data); }
                },
                {
                    targets: 11,
                    visible: false
                },
                {
                    targets: 12,
                    visible: false
                }
                //{ "width": "100px", "targets": [0] }
            ],
            select: {
                'style': 'multi+shift',
                'selector': 'td:first-child',
                "blurable": false,
                info: false
            },
            order: [[3, 'asc'], [4, 'asc']],
            "fnRowCallback": function (nRow, aData, iDisplayIndex) {
                var info = $(this).DataTable().page.info();
                $("td:nth-child(3)", nRow).html(info.start + iDisplayIndex + 1);
                return nRow;
            }
        });
    

    I have tried some adviced, like turn off autoWidth, set num% width ,use table-layout: fixed ,set static css into table , nothing work
    help me plese!
    thanks.

  • colincolin Posts: 12,600Questions: 0Answers: 2,154

    @systemsNatu You created a new thread here, please don't duplicate posts.

  • emersonstoriemersonstori Posts: 1Questions: 0Answers: 0

    Perhaps the problem is due to the number of columns, if there are too many it will not seem to work. Try to determine a size for the table for example:

    <

    table id = "tbl-PriceDiscrepancy" class = "table table-condensed table-hover" style = "width: 9000px">

    With this change my problem with column width disappeared

  • I_AM_AL_XI_AM_AL_X Posts: 4Questions: 0Answers: 0
    edited August 11

    Width does not work as a "columns" option for dynamic tables.
    Javascript like this:

    $(el).DataTable({
        data : myDataRows,
        columns : [
            { data : 0, width : "4em" },
            { data : 1, width : "30em" }
        ] } );
    

    Generates html that looks like this:

    <table style="width: 0px;">
      <thead>
        <tr>
          <th style="width: 0px;">
          ... etc ...
    

    I am working with "DataTables-1.10.25", downloaded July 2021.

    In my case, I do not attach the table's parent to the DOM until after the table has been constructed. This unattached state would foil any attempt by DataTables to take measurements directly on the table. But from the description of how DataTables works, it would seem no direct measurements are required. Furthermore, since my code is specifying "width", there is no reason to want to take a measurement.

    Bottom line: I am getting style="width: 0px;" instead of what I asked for.

  • colincolin Posts: 12,600Questions: 0Answers: 2,154

    @I_AM_AL_X We're happy to take a look, but as per the forum rules, please link to a test case - a test case that replicates the issue will ensure you'll get a quick and accurate response. Information on how to create a test case (if you aren't able to link to the page you are working on) is available here.

    Cheers,

    Colin

  • I_AM_AL_XI_AM_AL_X Posts: 4Questions: 0Answers: 0

    Test case:

    live.datatables.net/dilemaqa/1/edit?html,js,output

    Hope it is saved -- I was not able to "archive".

    The result is just as stated in my earlier post.

  • allanallan Posts: 54,680Questions: 1Answers: 8,552 Site admin

    But from the description of how DataTables works, it would seem no direct measurements are required.

    That is not the case. When you use columns.width DataTables will do a number of calculations.

    DataTables "needs" a width of 100% assigned to it (using CSS alone isn't enough, since it is virtually impossible to read a relative value from the document). Also you would likely want to append the element from table().container() to the document, which is the DataTable container, rather than just the table itself: http://live.datatables.net/dilemaqa/2/edit .

    Allan

  • cnankitcnankit Posts: 1Questions: 0Answers: 0

    In my case, this CSS property was the culprit
    white-space: nowrap;

    I change it to the following and the width property of Datatables worked as expected.
    white-space: break-spaces;

    Cheers!

  • I_AM_AL_XI_AM_AL_X Posts: 4Questions: 0Answers: 0

    Yes, the <table> element needs to have something like 'style="width:100%;". That fixed things, thank you.

    Regarding other comments, you advised:

    . . . append the element from "table().container()".

    I looked at the re-factored example; that helped me understand your advice. Instead of ...

    $("#my_container").append(tblEl).   // wrong
    

    ... I should take the instance created by DataTable and isolate the container created by DataTable, and put that container into "my_container". So, you wrote:

    $("#my-container").append(table.table().container());  //right
    

    Regarding my musings, you informed me that DataTable

    . . . will do a number of calculations.

    It looks like you are measuring the ratios of column widths for the "worst case" row, and then attempting to maintain that ratio when window size allows more width than required for the worst case. This is (at least one reason) why you need to do measurements; the ratios are based upon measurements.

    My initial thought was that the "worst case" measurements could be done within an unbounded container, and therefore the size context would not be needed. That would make sense provided ALL of the columns have an assigned, absolute width. But, now I realize that if ANY of the columns is not an absolute width, then the size context is important, in fact, indispensable. Hence, the "100%" (or something like it) is required.

    I am guessing that since, in my case, at the time of the measurements, the <table> is not part of the DOM, and therefore you have no context, the "100%" defaults to being 100% of the browser portal width. Not perfect, but usually good enough, and better than any other solution.

    I'm glad this works, because it would be impossible for me to provide an in-the-DOM context. My issue is that even if I put the <table> into its container, the container is within a sub-tree that is not attached to the DOM until later. Luckily, I expect the "#my_container" to have width similar to the portal. Also, I will probably be assigning absolute widths, or absolute min-widths, to ALL the columns, so the ratios will be knowable.

    Thank you for your quick response, your considerate explanation, and your helpful advice.

Sign In or Register to comment.