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

JavaScript 알림 상자를 화면 중앙에 배치하는 방법

JavaScript의 기본 alert() 함수는 브라우저가 직접 렌더링하기 때문에 위치나 디자인을 임의로 변경할 수 없습니다. 따라서 경고 메시지 상자를 화면 한가운데에 배치하려면 사용자 정의(Custom) 알림 상자를 직접 만든 뒤, CSS로 스타일을 지정하고 원하는 위치에 배치해야 합니다.

중앙 정렬은 CSS의 topleft 속성을 활용해 구현합니다. 일반적으로 두 속성 모두 50%로 설정하면 되지만, 아래 예제처럼 상자 안에 확인 버튼이 포함된 경우에는 시각적인 균형을 맞추기 위해 top 값을 40%로 조정하는 것이 좋습니다.

예제 코드

<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         function functionAlert(msg, myYes) {
            var confirmBox = $("#confirm");
            confirmBox.find(".message").text(msg);
            confirmBox.find(".yes").unbind().click(function() {
               confirmBox.hide();
            });
            confirmBox.find(".yes").click(myYes);
            confirmBox.show();
         }
      </script>
      <style>
         #confirm {
            display: none;
            background-color: #F3F5F6;
            color: #000000;
            border: 1px solid #aaa;
            position: fixed;
            width: 300px;
            height: 100px;
            left: 50%;
            margin-left: -100px;
            padding: 10px 20px 10px;
            box-sizing: border-box;
            text-align: center;
         }
         #confirm button {
            background-color: #FFFFFF;
            display: inline-block;
            border-radius: 12px;
            border: 4px solid #aaa;
            padding: 5px;
            text-align: center;
            width: 60px;
            cursor: pointer;
         }
         #confirm .message {
            text-align: left;
         }
      </style>
   </head>
   <body>
      <div id="confirm">
         <div class="message">This is a warning message.</div>
             <button class="yes">OK</button>
         </div>
      <input type="button" value="Click Me" onclick="functionAlert();" />
   </body>
</html>

핵심 포인트 정리

  • position: fixed; — 알림 상자를 뷰포트(viewport) 기준으로 고정하므로, 페이지를 스크롤해도 항상 같은 위치에 표시됩니다.
  • left: 50%; margin-left: -100px; — 상자의 왼쪽 끝을 화면 중앙(50%)에 맞춘 후, 너비의 절반만큼 다시 당겨와 수평 중앙 정렬을 완성합니다.
  • display: none과 show() — 상자는 평소 숨겨져 있다가, 버튼을 클릭하면 jQuery의 show() 메서드로 화면에 나타납니다.
  • unbind() 활용 — 이전에 등록된 클릭 이벤트를 제거한 뒤 새 콜백을 연결하여, 알림이 여러 번 호출되어도 이벤트가 중복 실행되지 않도록 합니다.

더 정확한 중앙 정렬을 위한 팁

위 예제처럼 음수 마진(margin-left)을 사용하는 방식은 상자의 너비가 고정되어 있어야 한다는 단점이 있습니다. 최신 CSS에서는 transform: translate(-50%, -50%)를 함께 사용하면 상자 크기와 관계없이 수직·수평 모두 정확한 중앙 정렬을 구현할 수 있습니다.

#confirm {
  position: fixed;
  left: 50%;
  top: 40%;
  transform: translate(-50%, -50%);
}

이 방식을 사용하면 반응형 웹 환경에서도 알림 상자가 항상 화면 중앙에 자연스럽게 배치되므로, 실무 프로젝트에서는 transform 기반 정렬을 권장합니다.