skip to Main Content

I have an HTML table with multiple columns:

<table id="req_header" border="2" style="overflow: auto;">
    <tr>
        <th><i class="fa fa-solid fa-check"></i></th>
        <th>Actual amount</th>
        <th>Current reading</th>
        <th>Employee</th>
        <th>Expected amount</th>
        <th>Installment</th>
        <th>Meter current date</th>
        <th>Meter previous date</th>
        <th>Previous reading</th>
        <th>Start from</th>
        <th>Total charge</th>
        <th>Type</th>
        <th>Unit consumed</th>
    </tr>
</table>

I am creating the rows dynamically and populating the cell values like this:

for(let data in snapshot){
    var row = table.insertRow(table.rows.length);
    var cell = row.insertCell(0);
    var cell1 = row.insertCell(1);
    var cell2 = row.insertCell(2);
    var cell3 = row.insertCell(3);
    var cell4 = row.insertCell(4);
    var cell5 = row.insertCell(5);
    var cell6 = row.insertCell(6);
    var cell7 = row.insertCell(7);
    var cell8 = row.insertCell(8);
    var cell9 = row.insertCell(9);
    var cell10 = row.insertCell(10);
    var cell11 = row.insertCell(11);
    var cell12 = row.insertCell(12);

    var input=document.createElement("INPUT");
    input.setAttribute("type", "checkbox");
    input.style.textAlign="center";
    cell.appendChild(input);

    var input=document.createElement("INPUT");
    input.style.textAlign="center";
    input.value = snapshot[data]["index"];
    cell1.appendChild(input);

    /* and so on, I am populating my table */
}

When I execute the code, my table shows like this:

enter image description here

As you can see the table crosses the screen width, as a result only half of the table is visible. Is there a way to reduce the table width, so that it fits the screen width? I cannot remove any of the columns, as all of them are important.

2

Answers


  1. You can set a horizontal scrollbar to avoid this problem. Wrap the table in a div tag and set it’s overflow property to scroll like this.

    .table-wrapper {
         overflow: scroll;
     }
    
    Login or Signup to reply.
  2. Update with CSS from the comments:

    td { 
        overflow: hidden; 
        text-overflow: ellipsis; 
        word-wrap: break-word;
    }
    

    For mobile phones I leave the table width but assign an additional CSS class to the table to enable horizontal scrolling (table will not go over the mobile screen anymore):

    @media only screen and (max-width: 480px) {
        /* horizontal scrollbar for tables if mobile screen */
        .tablemobile {
            overflow-x: auto;
            display: block;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search