参考にしたサイト

テーブルの横スクロール(スクロールヒントつき)の実装方法【スマホに最適】 | 株式会社リラクス
横スクロールできるテーブルの実装方法を解説します。ただ単に横スクロールできるだけではなく、「横にスクロールできます」と伝えるヒントウィンドウもアニメーション付きで表示されるため、利便性が高いです。コードはコピペOKです。
WordPress等に導入する場合、Functions.phpでテーブル挿入の部分を触るか、コードモードにしないとdivの挿入が難しそうなので、javascriptでTableタグの前後に自動で挿入するように変更した。
Javascript
document.addEventListener('DOMContentLoaded', () => {
const tables = document.querySelectorAll('table');
for (const table of tables) {
const newDiv = document.createElement("div");
newDiv.classList.add('table-container');
table.before(newDiv);
newDiv.append(table);
const scrollHint = document.createElement('div');
scrollHint.className = 'scroll-hint scroll-hint--show';
scrollHint.innerText = '横にスクロールできます';
newDiv.appendChild(scrollHint);
const showScrollHint = () => {
if (newDiv.scrollWidth > newDiv.clientWidth) {
scrollHint.classList.add('scroll-hint--show');
} else {
scrollHint.classList.remove('scroll-hint--show');
}
};
showScrollHint();
newDiv.addEventListener('scroll', () => {
scrollHint.classList.remove('scroll-hint--show');
});
}
});
スタイルシート
.table-container {
position: relative;
overflow-x: auto;
white-space: nowrap;
}
.table-container table {
border-collapse: collapse;
}
.scroll-hint {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 10px;
background: rgba(0, 0, 0, 0.5);
color: #fff;
font-weight: 700;
line-height: 1.4;
display: none;
animation: scroll-hint-animation 2s infinite ease;
}
@keyframes scroll-hint-animation {
0% {
transform: translate(-50%, -50%);
}
50% {
transform: translate(-40%, -50%);
}
100% {
transform: translate(-50%, -50%);
}
}
.scroll-hint--show {
display: block;
}