Created
August 26, 2021 13:11
-
-
Save elycruz/47f8b5e3fa91803958465c7b76ef4ffa to your computer and use it in GitHub Desktop.
Example of sticky table headers using 'position: sticky' for header columns.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
document.body.innerHTML = ` | |
<style> | |
table { | |
position: relative; | |
overflow: auto; | |
} | |
table, td, th { | |
border: 1px solid; | |
} | |
thead th { | |
position: sticky; | |
top: 0; | |
z-index: 2; | |
background: #fff; | |
} | |
.table1 thead th { | |
background: red; | |
} | |
.table2 thead th { | |
background: green; | |
} | |
.table3 thead th { | |
background: blue; | |
} | |
td, th { | |
padding: 1rem; | |
} | |
/* Allows example to scroll past tables */ | |
body { | |
height: 1000vh; | |
} | |
</style> | |
`; | |
var charsStart = '0'.charCodeAt(0), | |
charsEnd = 'z'.charCodeAt(0), | |
table1 = document.createElement('table'), | |
tbody = document.createElement('tbody'), | |
thead = document.createElement('thead'); | |
// Thead | |
// ---- | |
var tr = document.createElement('tr'); | |
for (var i = charsStart; i <= charsEnd; i += 1) { | |
var th = document.createElement('th'); | |
th.textContent = String.fromCharCode(i); | |
tr.appendChild(th); | |
} | |
thead.appendChild(tr); | |
// Tbody | |
// ---- | |
for (var j = 0; j < 10; j += 1) { | |
var tr = document.createElement('tr'); | |
for (var i = charsStart; i <= charsEnd; i += 1) { | |
var td = document.createElement('td'); | |
td.textContent = '----'; | |
tr.appendChild(td); | |
} | |
tbody.appendChild(tr); | |
} | |
table1.appendChild(thead); | |
table1.appendChild(tbody); | |
document.body.appendChild(table1); | |
' '.repeat('3').split('').forEach((_, i) => { | |
var t = table1.cloneNode(true); | |
t.classList.add(`table${i + 1}`); | |
document.body.appendChild(t); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment