Javascript, CSS - Modal

Modal

Posted by Yan on February 2, 2021

모달창 만들기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="src/styles.css" />
  </head>

  <body>
    <div id="app"></div>
    <h1>모달창 만들기</h1>

    <div class="subscribe-section">
      <h2>This is modal</h2>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias,
        illo. Sunt odit architecto veritatis tenetur deserunt faci
      </p>
      <button class="modal-btn">Modal</button>
    </div>

    <div class="modal-bg">
      <div class="modal">
        <h2>구독하기</h2>
        <label for="name">이름: </label>
        <input type="text" name="name" />
        <label for="email">이메일: </label>
        <input type="email" name="email" />
        <button class="subscribe">구독하기</button>
        <span class="modal-close">X</span>
      </div>
    </div>

    <script src="src/index.js"></script>
  </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
body {
  font-family: sans-serif;
}

.modal-bg {
  position: fixed;
  width: 100%;
  height: 100vh;
  //width와 height가 100이라서 모달창 밖의 어두운 부분을 클릭을 해도 클릭에 반응하지 않는다.
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s, opacity 0.5s;
}

.bg-active {
  visibility: visible;
  opacity: 1;
}

.modal {
  background-color: white;
  width: 30%;
  height: 30%;
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-direction: column;
  position: relative;
  //modal-close를 모달  안에 들어오게 하려면 position absolute되어 있는 modal-close 상위에 position:relative를 준다.
}

.subscribe {
  margin: 10px;
}

.modal-close {
  position: absolute;
  top: 10px;
  right: 10px;
  font-weight: bold;
  cursor: pointer;
}
1
2
3
4
5
6
7
8
9
10
11
const modalBtn = document.querySelector(".modal-btn");
const modalBg = document.querySelector(".modal-bg");
const modalClose = document.querySelector(".modal-close");

modalBtn.addEventListener("click", () => {
  modalBg.classList.add("bg-active");
});

modalClose.addEventListener("click", () => {
  modalBg.classList.remove("bg-active");
});

알게 된 것

  1. visibility: hidden -> visible로 보이거나 보이지 않게 할 수 있다.

opacity:0 -> opacity:1 포함

  1. transition: visibility 0s, opacity 0.5s이런 식으로 쓴다

  2. position:absolute 상위에 position:relative를 주면 하위의 element는 상위 element의 position에 따른다.