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

Cách tạo và áp dụng CSS cho JavaScript Alert box

Alert mặc định không áp dụng CSS được. Phải tạo custom alert box (modal) rồi style bằng CSS.

Ví dụ Custom Alert có style (Vanilla JS)

<!DOCTYPE html>
<html>
<head>
<style>
.alert-overlay { display:none; position:fixed; inset:0; background:rgba(0,0,0,0.4); z-index:1000; backdrop-filter:blur(2px); }
.alert-box { position:fixed; top:50%; left:50%; transform:translate(-50%,-50%);
    background:#F3F5F6; color:#000; padding:24px; border-radius:12px; width:90%; max-width:360px;
    box-shadow:0 8px 30px rgba(0,0,0,0.15); text-align:center; font-family:system-ui, sans-serif; }
.alert-message { margin-bottom:20px; line-height:1.6; }
.alert-btn { background:#1976d2; color:#fff; border:none; border-radius:8px; padding:10px 28px;
    font-size:1rem; font-weight:600; cursor:pointer; transition:background .2s; }
.alert-btn:hover { background:#1565c0; }
</style>
</head>
<body>
    <button onclick="showAlert('Custom alert với CSS đẹp mắt!')">Mở Alert</button>
    <div class="alert-overlay" id="alertOverlay">
        <div class="alert-box">
            <div class="alert-message" id="alertMsg"></div>
            <button class="alert-btn" onclick="hideAlert()">OK</button>
        </div>
    </div>
    <script>
        function showAlert(msg) {
            document.getElementById('alertMsg').textContent = msg;
            document.getElementById('alertOverlay').style.display = 'block';
        }
        function hideAlert() {
            document.getElementById('alertOverlay').style.display = 'none';
        }
        document.getElementById('alertOverlay').addEventListener('click', e => {
            if (e.target.id === 'alertOverlay') hideAlert();
        });
        document.addEventListener('keydown', e => { if (e.key === 'Escape') hideAlert(); });
    </script>
</body>
</html>

CSS quan trọng: overlay full-screen, box centered, animation, z-index cao, responsive width.