JavaScript 경고창을 화면 중앙에 띄우는 방법
기본 alert() 함수는 브라우저가 제공하는 고정된 형태의 대화상자이기 때문에 위치를 조정할 수 없습니다. 따라서 경고창을 화면 중앙에 표시하려면 커스텀(Custom) 경고창을 직접 만들어야 합니다.
커스텀 경고창은 HTML과 CSS로 박스를 구성한 뒤, CSS의 position: fixed; 속성과 함께 top, left 속성을 활용해 원하는 위치에 배치할 수 있습니다.
핵심 원리
- 일반적으로 요소를 화면 중앙에 배치하려면
top과left값을 50%로 설정합니다. - 다만 아래 예제처럼 버튼 등 다른 요소와의 정렬을 맞춰야 하는 경우에는 값을 40%로 조정하여 시각적인 균형을 맞출 수 있습니다.
예제 코드
아래는 jQuery를 활용해 커스텀 확인창을 만들고, 이를 화면 중앙 근처에 표시하는 완전한 예제입니다.
<!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: 40%;
top: 40%;
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><br>
<button class="yes">OK</button>
</div>
<input type="button" value="Click Me" onclick="functionAlert();" />
</body>
</html>코드 설명
1. 커스텀 확인창 구조#confirm이라는 ID를 가진 div가 경고창 역할을 합니다. 내부에는 메시지를 표시하는 .message 영역과 사용자가 클릭할 .yes 버튼이 포함되어 있습니다.
2. 화면 중앙 배치
CSS에서 position: fixed;로 설정하고 left: 40%, top: 40%을 지정했습니다. 이렇게 하면 창 크기와 관계없이 항상 같은 위치에 경고창이 나타납니다. 정확한 중앙 정렬이 필요하다면 두 값을 모두 50%로 변경하면 됩니다.
3. 동작 방식functionAlert() 함수가 호출되면 메시지를 설정하고 확인창을 화면에 표시(show())합니다. OK 버튼을 클릭하면 확인창이 사라지며(hide()), 필요하다면 콜백 함수(myYes)를 전달해 추가 동작을 실행할 수도 있습니다.
정리
브라우저 기본 alert()은 스타일링이 불가능하므로, 커스텀 경고창을 만들어 position: fixed와 top/left 속성으로 위치를 제어하는 것이 가장 확실한 방법입니다. 이 방식을 응용하면 디자인에 맞는 세련된 알림창, 확인창, 모달 창을 자유롭게 구현할 수 있습니다.