Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách hiển thị alert box ở giữa màn hình (center) bằng JavaScript

Tạo custom alert, dùng CSS top:50%; left:50%; transform:translate(-50%,-50%) để căn giữa chính xác.

Ví dụ

<!DOCTYPE html>
<html>
<head>
<style>
.alert-overlay { display:none; position:fixed; inset:0; background:rgba(0,0,0,0.4); z-index:1000; }
.alert-box { position:fixed; top:50%; left:50%; transform:translate(-50%,-50%);
    background:#F3F5F6; color:#000; padding:20px; border:1px solid #aaa; border-radius:8px;
    width:300px; height:100px; text-align:center; box-shadow:0 4px 20px rgba(0,0,0,0.2); }
.alert-box button { background:#fff; border:4px solid #aaa; border-radius:12px; padding:5px 15px; cursor:pointer; }
</style>
</head>
<body>
    <button onclick="showAlert()">Mở Alert giữa màn hình</button>
    <div class="alert-overlay" id="alertOverlay">
        <div class="alert-box">
            <div class="message">Alert ở giữa màn hình!</div><br>
            <button onclick="hideAlert()">OK</button>
        </div>
    </div>
    <script>
        function showAlert() { document.getElementById('alertOverlay').style.display='block'; }
        function hideAlert() { document.getElementById('alertOverlay').style.display='none'; }
        document.getElementById('alertOverlay').onclick = e => { if(e.target.id==='alertOverlay') hideAlert(); };
    </script>
</body>
</html>

Mẹo: Nếu alert có nút ở dưới, dùng top:40% hoặc transform:translate(-50%,-60%) để cân bằng trực quan.