モーダル

INDEX

説明

ボタンを押すとモーダルが表示されます。

手順

手順1

HTML要素を用意します

モーダルを表示させるボタンと、モーダルの要素を追加します。

/* ボタン */
<div class="wrapper">
  <button id="btn" class="btn">モーダルを表示する</button>
</div>

/* モーダル */
<div id="modal" class="modal">
  <div class="modal__content">
    <h2 class="modal__title">タイトル</h2>
    <div class="modal__text">この文章はダミーです。文字の大きさ、量、字間、行間等を確認するために入れています。この文章はダミーです。文字の大きさ、量、字間、行間等を確認するために入れています。この文章はダミーです。文字の大きさ、量、字間、行間等を確認するために入れています。</div>
    <div id="close" class="close">
      <span class="close__line1"></span>
      <span class="close__line2"></span>
    </div>
  </div>
</div>

手順2

CSSで要素をスタイリングします。

.modal {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  display: none;
  place-content: center;
  background-color: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(2px);
  
  &__content {
    background-color: #fff;
    width: 60%;
    border-radius: 12px;
    padding: 32px;
    margin: 0 auto;
    position: relative;
  }
  
  &__title {
    color: #eb6100;
    line-height: 1;
  }
  
  &__text {
    color: #6d6d6d;
  }
}

.close {
  position: absolute;
  width: 20px;
  height: 20px;
  top: 9%;
  right: 3%;
  transition: opacity 0.4s ease;
  
  &:hover {
    opacity: 0.6;
  }
  
  &__line1 {
    display: inline-block;
    width: 100%;
    height: 2px;
    background-color: #000;
    position: absolute;
    transform: rotate(45deg);
  }
  
  &__line2 {
    display: inline-block;
    width: 100%;
    height: 2px;
    position: absolute;
    background-color: #000;
    transform: rotate(-45deg);
  }

手順3

JavaScriptで以下の処理を行います。

  1. ボタンをクリックするとモーダルを表示させる。
  2. Xをクリックするとモーダルを取り除く。
  3. モーダルの外側をクリックするとモーダルを取り除く。
const btn = document.getElementById("btn");
const close = document.getElementById("close");
const modal = document.getElementById("modal");

const removeModal = () => modal.style.display = "none";

// ボタンをクリック
btn.addEventListener("click", () => {
  modal.style.display = "grid";
})

// Xをクリック
close.addEventListener("click", () => {
  removeModal();
})

// モーダルの外側をクリック
modal.addEventListener("click", (e) => {
  if (e.target === modal) removeModal();
});

サンプル

参考

PREV

LAB一覧

NEXT

最新記事 Latest