Exemple de table HTML défilante avec en-tête figé

Table défilante verticalement et horizontalement avec en-tête utilisant la propriété css "position:sticky".

La première colonne et l'en-tête sont figés.

Exemple


* testé uniquement avec Firefox

Code

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<html lang="fr">

<style>

table,

th,

td {

border-collapse: separate;

border-spacing: 0px;

position: relative;

font-family: 'Helvetica Neue", Helvetica, Arial'

}

table tr:first-child th {

border-top: 1px solid white;

}

table tr th:first-child,

table tr td:first-child {

border-left: 1px solid white;

}

table tr td:first-child {

font-weight: bold;

}

table tr th,

table tr td {

border-bottom: 1px solid white;

border-right: 1px solid white;

white-space: nowrap;

}

table tr:nth-child(2n) td {

background: #e9e9e9;

}

table tr:nth-child(2n+1) td {

background: #f6f6f6;

}

table>thead {

position: sticky;

top: 0;

z-index: 2;

background: #2980b9;

color: white;

}

table>tbody>tr>td:nth-child(1),

table>thead>tr>th:nth-child(1) {

position: sticky;

left: 0;

z-index: 1;

}

table>thead>tr>th:nth-child(1) {

background: #2980b9;

z-index: 3;

}

</style>

</head>

<body>

<div>

<h1>

En-tête

</h1>

</div>

<div style='max-height:200px;max-width:300px;overflow:auto;'>

<table>

<thead>

<tr>

<th colspan="4">Date</th>

</tr>

<tr>

<th>Année</th>

<th>Mois</th>

<th>Jour</th>

<th>Texte</th>

</thead>

<tbody>

</tr>

</tbody>

</table>

</div>

<div>

<h1>

Bas de page

</h1>

</div>

<script>

const optionsDate = {

weekday: "long",

year: "numeric",

month: "long",

day: "numeric"

};

const table = document.querySelector('table tbody');

let cpt, jourInitial = new Date(new Date().getFullYear(), 0, 1);

for (cpt = 0; cpt < 1000; cpt++) {

jour = new Date(jourInitial.getFullYear(), jourInitial.getMonth(), jourInitial.getDate() + cpt);

const ligne = table.insertRow(cpt);

const celluleAnnee = ligne.insertCell(0);

const celluleMois = ligne.insertCell(1);

const celluleJour = ligne.insertCell(2);

const celluleJourTexte = ligne.insertCell(3);

celluleAnnee.innerText = jour.getFullYear();

celluleMois.innerText = jour.toLocaleDateString('fr-fr', { month: "numeric" });

celluleJour.innerText = jour.getDate();

celluleJourTexte.innerText = jour.toLocaleDateString('fr-fr', optionsDate);

}

</script>

</body>

</html>