Maximum column width for all columns

Maximum column width for all columns

ludwigmludwigm Posts: 12Questions: 8Answers: 1

How can I set a maximum width for all columns?
The table is generated dynamically, I can´t tell with column has too much content. Currently, a column with many characters takes up so much space that the table has to be scrolled in x-direction. If the max width is exceeded, there should be a line break.
I tried, with no visible effect:

var columnDefs = [
    {
        width: '50px',
        targets: '_all'
    }
];

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 62,858Questions: 1Answers: 10,344 Site admin
    Answer ✓

    How can I set a maximum width for all columns?

    Normally you can't directly - that isn't how HTML tables work. However, there are two options:

    1. table-layout: fixed will give you pixel perfect control over the table column widths using the table-layout CSS property. The downside is that the table doesn't adjust for mistakes and often content will overflow.
    2. Wrap the content of the table cells in a div (which you could do with a rendering function) and apply the max-width to that.

    Allan

  • ludwigmludwigm Posts: 12Questions: 8Answers: 1

    I chose the second option:

     // Calculate the targets for table cell content div, excluding the last column
    var div_targets = columns.map((col, index) => index).slice(0, -1);
    var columnDefs = [   
        // wrap cell content to div, in order to manage max-width            
        {
            "targets": div_targets,
            "render": function (data, type, row, meta) {
                return '<div class="tablecell-content">' + data + '</div>';
            }
    ]
    
    <style>
      .tablecell-content {
          max-width: 300px; /* Set your desired max width */
          word-wrap: break-word; /* Allow text to wrap to new lines */
          white-space: normal; /* Ensure text wraps */
      }
    </style>
    
Sign In or Register to comment.