Sticky Header in Overflow Div

by bretonics

HTML

<script src="https://code.jquery.com/jquery-3.4.1.slim.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css">
<div class="container-fluid">
    <div>
        <h1>Sticky Header in Overflow Div</h1>
        <div class="d1">
            <table class="table t1">
                <thead>
                    <tr>
                        <th>Foo</th>
                        <th>BarBarBar</th>
                        <th>FoofooFoo</th>
                        <th>BarBarBar</th>
                        <th>FooFoo</th>
                        <th>BarBarBar</th>
                        <th>FoofooFoo</th>
                        <th>BarBar</th>
                        <th>FoofooFoo</th>
                        <th>BarBarBar</th>
                        <th>FoofooFoo</th>
                        <th>Bar</th>
                        <th>FoofooFoo</th>
                        <th>BarBarBar</th>
                        <th>FoofooFoo</th>
                        <th>BarBarBar</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <th>a</th>
                        <td>1</td>
                        <td>2</td>
                        <td>3</td>
                        <td>a</td>
                        <td>1</td>
                        <td>2</td>
                        <td>3</td>
                        <td>a</td>
                        <td>1</td>
                        <td>2</td>
                        <td>3</td>
                        <td>a</td>
                        <td>1</td>
                        <td>2</td>
                        <td>3</td>
         ...

CSS

th {
  padding: 20px 100px;
  background: #5af;
}

thead th {
    position: sticky !important;
    top: 0px;
    z-index: 1000;
}

tbody th {
    position: -webkit-sticky; /* for Safari */
    position: sticky;
    left: 0;
    z-index: 1;
}

thead th:first-child {
    position: sticky;
    top: 0;
    left: 0;
    z-index: 3;
}

/* thead th:first-child { */
thead th:not(:first-child) {
    position: sticky;
    left: 0;
    z-index: 1;
}


.d1 {
    max-width: 100%;
    max-height: 100%;
    overflow-x: auto;
}

.t1 {
    table-layout: fixed;
    display: block;
    /* overflow: auto; */
    border-collapse: collapse;
}

.sticky thead > tr > th {
    position: -webkit-sticky;
    position: sticky;
    top: 100;
    z-index: 2;
}