Table scroll with HTML and CSS

Mohamed Naguib picture Mohamed Naguib · Feb 12, 2013 · Viewed 430.3k times · Source

I have a table like that which i fill with a data

<table id="products-table"  style="overflow-y:scroll" >
    <thead>
        <tr>
            <th>Product (Parent Product)</th> 
            <th>Associated Sites</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        @for (int i = 0; i < Model.Count(); i++)
        { 
        <tr>
            <td>
                <a href="Edit"><strong>@Model.ElementAt(i).Name</strong></a><br />
            </td>
            <td>
                <span class="lesser"></span>
            </td>
            <td>@Html.ActionLink("Edit Product", "Edit", "Products")<br />
                @Html.ActionLink("Associate Site", "Associate", "Products")
            </td>
         </tr>
        }
        <tr>
</tbody>
</table>

and CSS like that

    #products-table
{
     width: 200px;
    height: 400px;
    overflow:scroll;
}

but scroll doesn't work, I want to fix the height of the table and if it exceeds, then work with scrollbar

Answer

Garry picture Garry · Feb 12, 2013

Table with Fixed Header

<table cellspacing="0" cellpadding="0" border="0" width="325">
  <tr>
    <td>
       <table cellspacing="0" cellpadding="1" border="1" width="300" >
         <tr style="color:white;background-color:grey">
            <th>Header 1</th>
            <th>Header 2</th>
         </tr>
       </table>
    </td>
  </tr>
  <tr>
    <td>
       <div style="width:320px; height:80px; overflow:auto;">
         <table cellspacing="0" cellpadding="1" border="1" width="300" >
           <tr>
             <td>new item</td>
             <td>new item</td>
           </tr>
           <tr>
             <td>new item</td>
             <td>new item</td>
           </tr>
              <tr>
             <td>new item</td>
             <td>new item</td>
           </tr>
              <tr>
             <td>new item</td>
             <td>new item</td>
           </tr>
              <tr>
             <td>new item</td>
             <td>new item</td>
           </tr>
              <tr>
             <td>new item</td>
             <td>new item</td>
           </tr>
              <tr>
             <td>new item</td>
             <td>new item</td>
           </tr>
              <tr>
             <td>new item</td>
             <td>new item</td>
           </tr>
              <tr>
             <td>new item</td>
             <td>new item</td>
           </tr>
              <tr>
             <td>new item</td>
             <td>new item</td>
           </tr>
         </table>  
       </div>
    </td>
  </tr>
</table>

Result

Demo Image

This is working in all browser

Demo jsfiddle http://jsfiddle.net/nyCKE/6302/