モーダル内のみスクロールする方法

HTML/CSS/Sass

モーダルを表示した時、モーダル内のみスクロール可能にしたくて調べた記録です。

やり方

CSSでできます🙆‍♀️
スクロールさせたい要素の親要素に、以下のCSSプロパティを付与します。

overflow: scroll;

縦方向のスクロールだけ適用させたい場合は、Y軸指定をします。

overflow-y: scroll;

横方向だけに適用させる場合は、X軸を指定します。

overflow-x: scroll;

サンプル1

HTML

<div class="overlay">
  <div class="modal">
    <div class="modal-content">Content</div>
  </div>
</div>

CSS

.overlay {
  position: fixed;
  inset: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 50;
  background-color: rgba(0, 0, 0, 0.7);
}

.modal {
  width: 300px;
  height: 200px;
  padding: 16px;
  background-color: white;
  overflow: scroll; /* スクロール設定 */
}

.modal-content {
  min-height: 600px;
  background-color: lightblue;
}

サンプル2(モーダルの内側にpaddingをつける)

HTML

<div class="overlay">
  <div class="modal">
    <div class="modal-inner">
      <div class="modal-content">Content</div>
    </div>
  </div>
</div>

CSS

.overlay {
  position: fixed;
  inset: 0;
  margin: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 50;
  background-color: rgba(0, 0, 0, 0.7);
}

.modal {
  width: 300px;
  height: 200px;
  padding: 16px; /* モーダルの内側のpadding */
  background-color: white;
}

.modal-inner {
  height: 100%;
  overflow: scroll; /* スクロール設定 */
}

.modal-content {
  min-height: 600px;
  background-color: lightblue;
}

それでも上手くいかないとき

モーダル要素に高さ(height)が指定されていないと、適用されないことがあります。(X軸方向のスクロールだと幅(width)の指定が必要です)。

補足ですが、サンプル1、サンプル2共に、.modalクラスでheight: 200px;を指定しています。

タイトルとURLをコピーしました