Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript와 CSS만으로 모달 팝업 만드는 방법 (완전 정복 가이드)

모달 팝업이란?

모달 팝업은 버튼을 클릭했을 때 화면 위에 나타나는 대화상자(Dialog Box)입니다. 일반적으로 팝업이 열려 있는 동안에는 배경 콘텐츠와의 상호작용이 차단되며, 사용자가 팝업 바깥 영역을 클릭하거나 닫기 버튼을 누르면 자동으로 닫히도록 구현합니다.

아래는 헤더(Header)와 본문 텍스트가 포함된 기본적인 모달 팝업의 모습입니다. 필요에 따라 하단에 푸터(Footer) 영역을 추가하는 것도 가능합니다.

JavaScript와 CSS만으로 모달 팝업 만드는 방법 (완전 정복 가이드)

CSS와 JavaScript를 활용한 모달 팝업 구현하기

아래 전체 코드를 복사하여 HTML 파일로 저장한 뒤 브라우저에서 실행하면, 버튼 클릭 시 하단에서 슬라이드되어 올라오는 애니메이션 효과가 적용된 모달 팝업을 확인할 수 있습니다.

예제 코드

<!DOCTYPE html>
<html>
   <head>
      <style>
         .popup {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: #F1F1F1;
            background-color: rgba(0,0,0,0.4);
            -webkit-animation-name: fadeIn;
            -webkit-animation-duration: 0.4s;
            animation-name: fadeIn;
            animation-duration: 0.4s
         }
         .popup-content {
            position: fixed;
            bottom: 0;
            background-color: #ffffff;
            width: 100%;
            -webkit-animation-name: slideIn;
            -webkit-animation-duration: 0.5s;
            animation-name: slideIn;
            animation-duration: 0.5s
         }
         .end {
            color: white;
            float: right;
            font-size: 15px;
            font-weight: bold;
         }
         .end:hover,
         .end:focus {
            color: #000;
            text-decoration: underline;
            cursor: pointer;
         }
         .popup-header {
            padding: 1px 10px;
            background-color: #8AC1E0;
            color: white;
         }
         .popup-body {padding: 1px 5px;}
         @-webkit-keyframes slideIn {
            from {bottom: -300px; opacity: 0}
            to {bottom: 0; opacity: 1}
         }
         @keyframes slideIn {
            from {bottom: -300px; opacity: 0}
            to {bottom: 0; opacity: 1}
         }
         @-webkit-keyframes fadeIn {
            from {opacity: 0}
            to {opacity: 1}
         }
         @keyframes fadeIn {
            from {opacity: 0}
            to {opacity: 1}
         }
      </style>
   </head>
   <body>
      <h2>Heading</h2>
      <button id="btn">Click for Popup</button>
      <div id="myModal" class="popup">
         <!-- Modal content -->
         <div class="popup-content">
            <div class="popup-header">
               <span class="end">×</span>
               <h2>Header</h2>
            </div>
            <div class="popup-body">
               <p>Demo Text</p>
            </div>
         </div>
      </div>
      <script>
         var popup = document.getElementById('myModal');
         var myBytton = document.getElementById("btn");
         var span = document.getElementsByClassName("end")[0];
         myBytton.onclick = function() {
            popup.style.display = "block";
         }
         span.onclick = function() {
            popup.style.display = "none";
         }
         window.onclick = function(event) {
            if (event.target == popup) {
               popup.style.display = "none";
            }
         }
      </script>
   </body>
</html>

코드 작동 원리 살펴보기

위 예제가 어떻게 동작하는지 핵심 부분만 짚어보겠습니다.

1. 오버레이 배경 (.popup)

.popup 클래스는 position: fixed;z-index: 1;을 사용해 화면 전체를 덮는 오버레이 역할을 합니다. 기본 상태는 display: none;으로 숨겨져 있다가, 반투명한 어두운 배경색인 rgba(0,0,0,0.4) 덕분에 팝업 뒤쪽 콘텐츠가 은은하게 비쳐 보이게 됩니다.

2. 부드러운 등장 애니메이션 (@keyframes)

fadeIn 애니메이션이 배경을 서서히 밝혀 주고, slideIn 애니메이션은 팝업 콘텐츠가 화면 하단(-300px)에서 자연스럽게 올라오도록 만듭니다. -webkit- 접두사가 함께 작성된 이유는 Safari 등 구형 웹킷 기반 브라우저와의 호환성을 확보하기 위함입니다.

3. JavaScript 이벤트 처리

  • 팝업 열기: 버튼(#btn)을 클릭하면 popup.style.display = "block";이 실행되어 모달이 화면에 나타납니다.
  • X 버튼으로 닫기: 헤더 우측 상단의 × 아이콘(.end)을 클릭하면 display 속성이 다시 none으로 변경됩니다.
  • 외부 영역 클릭으로 닫기: window.onclick 이벤트에서 클릭된 대상(event.target)이 오버레이 자신(popup)과 같은 경우에만 팝업을 닫습니다. 이 조건 덕분에 팝업 내부 콘텐츠를 클릭했을 때는 창이 닫히지 않습니다.

마무리 및 활용 팁

이처럼 별도의 라이브러리 없이 순수 HTML, CSS, JavaScript만으로도 완성도 높은 모달 팝업을 손쉽게 만들 수 있습니다. 실제 프로젝트에 적용할 때는 다음과 같은 확장도 고려해 보세요.

  • ESC 키 지원: keydown 이벤트를 추가해 키보드로도 팝업을 닫을 수 있게 하면 접근성이 향상됩니다.
  • 중앙 정렬 레이아웃: .popup-contentbottom: 0; 대신 Flexbox를 활용하면 화면 한가운데 뜨는 전통적인 모달 형태로 변경할 수 있습니다.
  • 닫힌 후 포커스 관리: 팝업이 닫힐 때 다시 버튼으로 포커스를 이동시키면 키보드 사용자 경험이 개선됩니다.