Open In App

How to show JavaScript alert box in the middle of the screen?

To create an alert box that occurs in the middle of the browser window we use CSS to style the alert box and JavaScript to control its appearance. Techniques include adjusting the alert box's position using CSS properties as well as JavaScript event handling to trigger the alert box's display to enhance user experience by ensuring that important alerts are displayed and easily visible to users.

Approach

Example: The code below shows an alert box in the middle of the screen using CSS and JavaScript.

<!DOCTYPE html>
<html>

<head>
    <title>Centered Alert Box</title>
    <style>
        body {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }

        #alert {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            padding: 20px;
            background-color: #f0f0f0;
            border: 1px solid #ddd;
        }

        .heading {
            color: green;
            font-size: 40px;
        }
    </style>
</head>

<body>
    <h1 class="heading">
      GeeksForGeeks
      </h1>
    <h4> alert box in the middle Using CSS with Custom HTML</h4>

    <button id="show-alert">Show Alert</button>

    <div id="alert">
        <p>This is a centered alert message!</p>
        <button onclick="document.getElementById('alert')
                                   .style.display = 'none'">
                      Close
          </button>
    </div>

    <script>
        
          // Add an event listener to the "Show Alert" button
        document.getElementById('show-alert')
                  .addEventListener('click', function () {
            document.getElementById('alert')
                      .style.display = 'block';
        });
    </script>

</body>

</html>

Output:

Untitled-design-(11)

Output

Article Tags :