naik3 naik3 - 2 months ago 11
Javascript Question

How to fix HTML table cell width?

I am trying to fix the width of HTML table cell. Suppose the in a row 5 cells are there all should of same width, if new cells getting added, width should be same but horizontal scroll bar should come. Here is W3school example which am trying. Please helep me to solve this problem. One can see in that example, after adding some 12 to 15 cells, cells size is reducing, after adding some more cells then scroll bar will come.

Here is my css what i have tried:

table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
table-layout: fixed;
word-break: break-all;
}

td, th {
border: 1px solid #dddddd;
text-align: center;
padding: 8px;
width: 65%;
margin-bottom: 50px;
}
tr:nth-child(even) {
background-color: #dddddd;
}

Answer

here how i solved your issue, here is working demo of it. you can run and check it that it working.

if you give css like

table{
width:100%;
} 

then this become too dirty, because it divide whole table size into 100%, so there's scrolling in <th> appear.

function myFunction() {
    var row = document.getElementById("myRow");
    var x = row.insertCell(0);
    x.innerHTML = "New cell";
}
table, td {
    border: 1px solid black;
     min-width: 90px;
     overflow:auto;
}
<p>Click the button to insert new cell(s) at the beginning of the table row.</p>

<table>
  <tr id="myRow">
    <td>First cell</td>
    <td>Second cell</td>
    <td>Third cell</td>
    <td>fourth cell</td>
    <td>First cell</td>
    <td>Second cell</td>
    <td>Third cell</td>
    <td>fourth cell</td>
   <td>Second cell</td>
    <td>Third cell</td>
    <td>fourth cell</td>
    </tr>
  </table>
<button onclick="myFunction()">Try it</button>