naik3
naik3

Reputation: 309

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;
}

Upvotes: 0

Views: 902

Answers (2)

yash
yash

Reputation: 2291

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>

Upvotes: 1

Denny Sutedja
Denny Sutedja

Reputation: 538

css:

table, td {
    border: 1px solid black;
    min-width: 80px;
    overflow: auto;
}

or

table, td {
    border: 1px solid black;
}
#myRow > td {
    min-width: 80px;
    overflow: auto;
}

in your case:

table {
/* width must auto or none */
width:auto;
font-family: arial, sans-serif;
border-collapse: collapse;
table-layout: fixed;
word-break: break-all;
}

#myRow > td {
    border: 1px solid black;
    min-width: 80px;
    overflow: auto;
}

Upvotes: 2

Related Questions