Ratan Ratan - 2 months ago 5
CSS Question

How to apply width 100% with scroll able table body

I am trying to implement the table body scrollable. I am able to successfully did it but now I am facing issue with width 100%

Please check this jsfiddle https://jsfiddle.net/Ratan_Paul/stpgd6x6/



<table>
<thead style="display:block;">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
</thead>
<tbody style="max-height: 50px;display: block;overflow-y:auto;">
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
</tbody>
</table>





Can't I apply the width to thead and tbody ? any solution so I can use the scroll as well as set the width to 100%

Answer

You'll need to clear a few styles that initially come with tables as well as set a width of 33% since you're using 3 column headers (100%/3)

See below:

table {
    width: 100%;
    border-collapse: collapse;
    border-spacing: 0;
    border: 2px solid black;
}

thead, tbody, tr, td, th { display: block; }

tr:after {
    content: ' ';
    display: block;
    visibility: hidden;
    clear: both;
}

thead th { 
    height: 30px;
    line-height: 30px;
    text-align: left;
}

tbody {
    height: 100px;
    overflow-y: auto;
}

thead {
    /* fallback */
    width: 97%;
    /* minus scroll bar width */
    width: calc(100% - 17px);
}

tbody { border-top: 2px solid black; }

tbody td, thead th {
    width: 33%;
    float: left;
}

tbody td:last-child, thead th:last-child {
    border-right: none;
}
<table>
<thead>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
 </thead>
 <tbody>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
  </tbody>
</table>

More detailed answer can be found here: HTML table with 100% width, with vertical scroll inside tbody

Comments