I am trying to make a table with fixed header and a scrollable content using the bootstrap 3 table. Unfortunately the solutions I have found does not work with bootstrap or
Simply position: sticky; top: 0;
your th
elements. (Chrome, FF, Edge)
.tableFixHead { overflow-y: auto; height: 100px; }
.tableFixHead thead th { position: sticky; top: 0; }
/* Just common table stuff. Really. */
table { border-collapse: collapse; width: 100%; }
th, td { padding: 8px 16px; }
th { background:#eee; }
TH 1 TH 2
A1 A2
B1 B2
C1 C2
D1 D2
E1 E2
Since border
cannot be painted properly on a translated TH
element,
to recreate and render "borders" use the box-shadow
property:
/* Borders (if you need them) */
.tableFixHead,
.tableFixHead td {
box-shadow: inset 1px -1px #000;
}
.tableFixHead th {
box-shadow: inset 1px 1px #000, 0 1px #000;
}
.tableFixHead { overflow-y: auto; height: 100px; }
.tableFixHead thead th { position: sticky; top: 0; }
/* Just common table stuff. Really. */
table { border-collapse: collapse; width: 100%; }
th, td { padding: 8px 16px; }
th { background:#eee; }
/* Borders (if you need them) */
.tableFixHead,
.tableFixHead td {
box-shadow: inset 1px -1px #000;
}
.tableFixHead th {
box-shadow: inset 1px 1px #000, 0 1px #000;
}
TH 1 TH 2
A1 A2
B1 B2
C1 C2
D1 D2
E1 E2
You can use a bit of JS and translateY the th
elements
jQuery example
var $th = $('.tableFixHead').find('thead th')
$('.tableFixHead').on('scroll', function() {
$th.css('transform', 'translateY('+ this.scrollTop +'px)');
});
.tableFixHead { overflow-y: auto; height: 100px; }
/* Just common table stuff. */
table { border-collapse: collapse; width: 100%; }
th, td { padding: 8px 16px; }
th { background:#eee; }
TH 1 TH 2
A1 A2
B1 B2
C1 C2
D1 D2
E1 E2
Or plain ES6 if you prefer (no jQuery required):
// Fix table head
function tableFixHead (e) {
const el = e.target,
sT = el.scrollTop;
el.querySelectorAll("thead th").forEach(th =>
th.style.transform = `translateY(${sT}px)`
);
}
document.querySelectorAll(".tableFixHead").forEach(el =>
el.addEventListener("scroll", tableFixHead)
);