Disera Disera - 6 months ago 38
Javascript Question

CSS - Is it possible to freeze the header on top of html table from scrolling using pure CSS?

I have been trying to freeze my header on Top, from scrolling down. I tried the below code using css, but unsuccessful.
Please suggest a way to do it.

My code:

document.write("<div align=\"left\" style=\"border:1px solid grey; float:left; overflow-y :scroll; margin-top:5px; margin-right:50px; height:410px; width:95%;\">");

document.write("<table border=1 height=100% width=100% margin-bottom:100px align=\"center\" cellspacing=0px style=\"width:350px;\">");
document.write("<thead bgcolor=\"#B8CCE5\" style=\"width:30px; \" >");
document.write("<tr style=\"display:table; width:100%; \"><th>Dates</th><th>Upgrade</th><th>Downloads</th><th nowrap width=100px>Total User Count</th></tr>");
document.write("</thead>");

document.write("<tbody style=\" display:block; max-height:365px; overflow-y:scroll; \">");
for(var i=0;i<dates.length;i++){
document.write("<tr style=\" \">");
document.write("<td nowrap align=center bgcolor=\"#DCE7EF\">"+dates[i]+"</td>");
document.write("<td nowrap align=center>"+name[i]+"</td>");
document.write("<td nowrap align=center>"+age[i]+"</td>");
document.write("<td nowrap align=center>"+count[i]+"</td>");
document.write("</tr>");
}
document.write("</tbody>");
document.write("</table>");
document.write("</div>");


I am stuck with this for weeks, Any help is really appreciated.Thanks in Advance.

Answer

You need to set display: block to thead and tbody. Then set overflow: auto to tbody.

table, th, td {
    border: 1px solid black;
}

table {
    width: 225px;
}

thead, tbody {
    display: block;
}

tbody {
    height: 120px;
    overflow: auto; 
}

th, td {
    width: 60px;
}
<table>
    <thead>
        <tr>
            <th>Head-1</th>
            <th>Head-2</th>
            <th>Head-3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td><td>2</td><td>3</td>
        </tr>
        <tr>
            <td>4</td><td>5</td><td>6</td>
        </tr>
        <tr>
            <td>7</td><td>8</td><td>9</td>
        </tr>
        <tr>
            <td>10</td><td>11</td><td>12</td>
        </tr>
        <tr>
            <td>13</td><td>14</td><td>15</td>
        </tr>
        <tr>
            <td>16</td><td>17</td><td>18</td>
        </tr>
        <tr>
            <td>19</td><td>20</td><td>21</td>
        </tr>
        <tr>
            <td>22</td><td>23</td><td>24</td>
        </tr>
        <tr>
            <td>25</td><td>26</td><td>27</td>
        </tr> 
        <tr>
            <td>28</td><td>29</td><td>30</td>
        </tr> 
    </tbody>
</table>

Comments