Make table scrollable and fix first and last columns

2.1k Views Asked by At

I have a table with below html

<div class="wrapper">
    <div class="tblWrapper">
        <table id="tbl">
            <thead>
                <tr>
                  <th class="first">header</th>
                  <th>header</th>
                  <th>header</th>...........<th class="last">header n</th>                        
                </tr>
            </thead>
            <tbody>
                <tr><td class="first"></td><td></td><td></td><td class="last"></td></tr>
            </tbody>
        </table>
    </div>
</div>

css

.wrapper{ position: relative; }
.tblWrapper{
    width: 98%;
    overflow-x: auto;
    overflow-y: hidden;
    white-space: nowrap;

    #tbl{ .first, .last{ position: absolute; } }
}

Want I am trying to achieve here is first and last columns should be fixed and rest of the columns must be scrollable.

The issue here is fixed columns overlaps with other columns and other issue is entire table is not fixed in the parent div width(having max-width: 630px;) its spreading out.

Any working around please..........

1

There are 1 best solutions below

2
On

You can use freezeHeader (A simple jquery plugin to freeze header row in html table) Reference

HTML :

<div class="wrapper">
    <div class="tblWrapper">
        <table id="tbl">
            <thead>
                <tr>
                  <th class="first">header</th>
                  <th>header</th>
                  <th>header</th>
                  <th class="last">header </th>                        
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>txt</td>
                    <td>txt</td>
                    <td> txtxtxtxtxtxtxtxtxt txtxtxtxtxtxtxtxtxt txtxtxtxtxtxtxtxtxt</td>
                    <td>txt</td>
                </tr>

                ...
                ...
                ...

                <tr>
                    <td>txt</td>
                    <td>txt</td>
                    <td>txt</td>
                    <td>txt</td>
                </tr>

            </tbody>
        </table>
    </div>
</div>

CSS :

thead tr th {
    border-top: 1px solid #E2E6E6;
    border-bottom: 3px solid #E5E5E5;
    vertical-align: middle;

}
th {
    color: white;
    background:gray;
}
th, td {
    text-align: left;
    padding: 5px 10px;
    border-bottom: 1px solid #E5E5E5;
}

Script :

    $(document).ready(function () {
        $("#tbl").freezeHeader();
    })

Jsfiddle demo