Open In App

How to Center the JavaScript Alert Message Box ?

To center the JavaScript alert message box, you can use CSS to define a custom alert box with fixed positioning and the transform property to adjust its position in the center of the viewport.

Approach

Example: The below code uses CSS properties to center the JavaScript alert message box.

<!DOCTYPE html>
<html>

<head>
    <style>
        body {
            text-align: center;
        }

        h1 {
            color: green;
        }

        .custom-alert {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #f1f1f1;
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
            display: none;
            max-width: 300px;
        }

        .custom-alert-title {
            font-weight: bold;
            margin-bottom: 10px;
        }

        .close-button {
            background-color: #f44336;
            color: white;
            border: none;
            border-radius: 5px;
            padding: 5px 10px;
            cursor: pointer;
        }

        .show-alert-button {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <h1>GeeksForGeeks</h1>
    <h3>Center the alert message box using CSS</h3>
    <button class="show-alert-button"
            onclick="showCustomAlert('Welcome to GeeksForGeeks!',
                    'This is a centered custom alert box.')">
      Show Custom Alert
      </button>

    <div class="custom-alert" id="customAlert">
        <div class="custom-alert-title" 
             id="customAlertTitle">
          </div>
        <span id="customAlertMessage"></span>
        <button class="close-button" 
                onclick="hideCustomAlert()">
          Close
          </button>
    </div>

    <script>
        function showCustomAlert(title, message) {
            let customAlert = 
                    document.getElementById('customAlert');
            let customAlertTitle = 
                    document.getElementById('customAlertTitle');
            let customAlertMessage = 
                    document.getElementById('customAlertMessage');

            customAlertTitle.innerText = title;
            customAlertMessage.innerText = message;
            customAlert.style.display = 'block';
        }

        function hideCustomAlert() {
            let customAlert = document.getElementById('customAlert');
            customAlert.style.display = 'none';
        }
    </script>
</body>

</html>

Output:

alb

Article Tags :