どうも、くまだです。
スクロールバーによるガタつきを解消するscrollbar-gutterプロパティについて。
scrollbar-gutterプロパティ
scrollbar-gutterプロパティはスクロールバーの幅分の余白を制御するプロパティです。
コードは以下になります。
<div class="l-container">
<p>scrollbar-gutter なし</p>
<div class="p-box">
<p>テキストテキスト</p>
<p>テキストテキスト</p>
<p>テキストテキストテキストテキスト</p>
</div>
<button class="c-button">ボタン</button>
<hr style="border:2px solid red;">
<p>scrollbar-gutter あり</p>
<div class="p-box p-box--gutter">
<p>テキストテキスト</p>
<p>テキストテキスト</p>
<p>テキストテキストテキストテキスト</p>
</div>
<button class="c-button">ボタン</button>
</div>
.l-container {
padding: 50px;
}
.p-box {
width: fit-content;
height: 150px;
border: 1px solid #000;
overflow: auto;
padding: 10px;
background-color: #f7f7f7;
}
.c-button {
background-color: orange;
padding: 10px;
margin-top: 10px;
}
.p-box.p-box--gutter {
scrollbar-gutter: stable;
}
document.addEventListener("DOMContentLoaded", function () {
const buttons = document.querySelectorAll(".c-button");
buttons.forEach(function(button) {
button.addEventListener("click", function () {
const box = button.previousElementSibling;
if (box && box.classList.contains("p-box")) {
const newParagraph = document.createElement("p");
newParagraph.textContent = "新しいテキスト";
box.appendChild(newParagraph);
}
});
});
});
See the Pen scrollbar-gutter by kuma0605 (@kuma0605) on CodePen.
ボタンをクリックすると、線で囲まれた要素内にpタグのテキストが生成されます。要素の高さは固定していて、要素の高さ以上のpタグがあるとスクロールバーが表示されます。
そのさいに、scrollbar-gutterプロパティを指定していないほうはスクロールバー表示のさいにガタつきがあり、指定しているほうはありません。
scrollbar-gutterプロパティを指定しているほうはあらかじめスクロールバー分の幅を確保した状態で表示されます。

〇 scrollbar-gutter プロパティの値
- auto : 初期値
- stable : スクロールバーが表示されないときでも、スクロールバー幅分の余白を確保する
- both-edges : 左側にも対照的にスクロールバー幅分の余白を確保
ここまで読んでくださりありがとうございました。