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

Cách đặt width/height cho alert box JavaScript

Alert mặc định không set kích thước được. Custom alert box dùng CSS width, height, max-width, min-height.

Ví dụ: Alert 300x100px

<!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; border:1px solid #aaa; border-radius:8px;
    width:300px; height:100px; /* Kích thước cố định */
    padding:10px 20px; box-sizing:border-box; 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 300x100</button>
    <div class="alert-overlay" id="alertOverlay">
        <div class="alert-box">
            <div class="message">Alert có kích thước cố đị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>

Responsive: Dùng width:90%; max-width:400px; min-height:auto; padding:1.5rem thay vì fixed px.